问题描述
我在写一个应用程序,我需要在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_SHIFT
或 KEY_CODE_A $ c $
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.
我当前的尝试使用类似于。问题是它只适用于可打印字符。如果所有的失败,我不是在硬编码的转换,但这将意味着我需要一个可能的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 - action:
Here's code to simulate a - action:
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef saveCommandDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, YES);
CGEventSetFlags(saveCommandDown, kCGEventFlagMaskCommand);
CGEventRef saveCommandUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)1, NO);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, saveCommandUp);
CFRelease(saveCommandUp);
CFRelease(saveCommandDown);
CFRelease(source);
A CGKeyCode
整数:
typedef uint16_t CGKeyCode; //From CGRemoteOperation.h
你真正的问题将是一个字符c> NSString )转换为键码。幸运的是,项目中的代码只需在文件。非常适合将字符串转换为键码,然后返回。
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中模拟按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!