Question: Question:
I'm doing OSX programming and want to generate a key sequence for a keyboard shortcut like Control-F4 in my app, but using CGEventCreateKeyboardEvent
and CGEventPost
doesn't work either. It worked fine when I used CGPostKeyboardEvent
to generate similar keystrokes. However, the CGPostKeyboardEvent
has become deprecated, so I'm looking for another way.
CGPostKeyboardEvent((CGCharCode)0, (CGKeyCode)118/*F4*/, true); // worked
CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(NULL, (CGKeyCode)118/*F4*/, true)); // doesn't work
I would appreciate it if you could tell me how to make it possible to execute keyboard shortcuts in an app like CGPostKeyboardEvent
. It's not surprising that the ability to issue system-related keyboard shortcuts like this is the reason why CGPostKeyboardEvent
has become deprecated …
Answer: Answer:
For example, I think you should do the following.
#import <Foundation/Foundation.h>
#import <Carbon/Carbon.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef f4 = CGEventCreateKeyboardEvent(source, kVK_F4, true);
CGEventSetFlags(f4, kCGEventFlagMaskControl);
CGEventTapLocation location = kCGHIDEventTap;
CGEventPost(location, f4);
CFRelease(f4);
CFRelease(source);
}
return 0;
}