在 Mac OS X 中模拟按键事件 [英] Simulating key press events in Mac OS X

查看:57
本文介绍了在 Mac OS X 中模拟按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,我需要在 Mac 上模拟按键事件,给定代表每个键的代码.看来我需要使用 CGEventCreateKeyboardEvent 函数来创建事件.问题是这个功能需要一个Mac键码,而我有的是一个代表特定键的代码.因此,例如,我收到:

I'm writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent function to create the event. The problem is that this function needs a Mac keycode, and what I have is a code that represents the specific key. So, for example, I receive:

KEY_CODE_SHIFTKEY_CODE_A - 这些都是在某处定义的数字常量.

KEY_CODE_SHIFT or KEY_CODE_A - these are both numeric constants defined somewhere.

我需要将这些常量转换为 CGKeyCode 值.

I need to take these constants and turn them into CGKeyCode values.

我目前的尝试使用类似于this SO question的代码.问题是它只适用于可打印的字符.如果所有其他方法都失败了,我不会对转换进行硬编码,但这意味着我需要一个可能的 CGKeyCode 值表,但我还没有找到.

My current attempt uses code similar to this SO question. The problem is that it only works for printable characters. If all else fails, I'm not above hard coding the conversion, but that would mean that I'd need a table of possible CGKeyCode values, which I have not yet been able to find.

有什么想法吗?

推荐答案

这是模拟 Cmd-S 动作的代码:

Here's code to simulate a Cmd-S action:

CGKeyCode inputKeyCode = kVK_ANSI_S;
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, inputKeyCode, NO);

CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);

CFRelease(saveCommandUp);
CFRelease(saveCommandDown);
CFRelease(source);

CGKeyCode 只不过是一个无符号整数:

A CGKeyCode is nothing more than an unsigned integer:

typedef uint16_t CGKeyCode;  //From CGRemoteOperation.h

您真正的问题是将字符(可能是 NSString)转换为键码.幸运的是,Shortcut Recorder 项目的代码可以在 SRKeyCodeTransformer.m 文件.它非常适合将字符串转换为键码并再次返回.

Your real issue will be turning a character (probably an NSString) into a keycode. Fortunately, the Shortcut Recorder project has code that will do just that in the SRKeyCodeTransformer.m file. It's great for transforming a string to a keycode and back again.

这篇关于在 Mac OS X 中模拟按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆