I need to simulate keystrokes in OSX. Here's how I do it:
-(void)execute {
CGEventSourceRef sourceRef =
CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef keyPress = CGEventCreateKeyboardEvent (sourceRef, (CGKeyCode)keyCode, true);
CGEventRef keyUnpress = CGEventCreateKeyboardEvent (sourceRef, (CGKeyCode)keyCode, false);
CGEventSetFlags(keyPress, modifierFlags);
CGEventPost(kCGHIDEventTap, keyPress);
//unpressing the acualkey
CGEventPost(kCGHIDEventTap, keyUnpress);
CFRelease(keyPress);
CFRelease(keyUnpress);
CFRelease(sourceRef);
}
It works fine for every hotkey or simple keystrokes in any app, but doesn't work for system wide shortcuts, for example option + space to launch Spotlight or cmd + shift + 4 to make a screenshot or ctrl + ` to open iTerm2 window.
I tried to change event's source and the location at which to post event, doesn't help. Any ideas?
See Question&Answers more detail:os