views:

1180

answers:

1

Hi,

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 recieve:

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

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

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.

Any ideas?

+3  A: 

Here's code to simulate a Cmd-S 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 is nothing more than an unsigned integer:

typedef uint16_t CGKeyCode;  //From CGRemoteOperation.h

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.

Dave DeLong
So in this example then, the `CGKeyCode` of `1` is the code for S? Also, would this work for just a foreground app, or if it was running in the background, would it work across the entire session? Thanks
joec
@joec yes to all of those.
Dave DeLong
So, say my app was running in the background (just as a service) and i had Photoshop in front, i could simulate a key press, and it would be seen in Photoshop? Thanks
joec
@joec yes, that's what would happen
Dave DeLong
thanks a lot for that.
joec
@Dave, do you have code that utilises SRKeyCodeTransformer? I have added the ShortcutRecorder framework to my project, but unsure really where to go from here. Thanks.
joec