I'm trying to simulate keyboard input Ctrl + Up to open the mission control, and referenced the code here:
https://stackoverflow.com/a/10745616/8556692
#import <Cocoa/Cocoa.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Open Mission Control");
CGEventSourceRef src =
CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
CGEventRef ctrld = CGEventCreateKeyboardEvent(src, 0x3B, true);
CGEventRef ctrlu = CGEventCreateKeyboardEvent(src, 0x3B, false);
CGEventRef upd = CGEventCreateKeyboardEvent(src, 0x7E, true);
CGEventRef upu = CGEventCreateKeyboardEvent(src, 0x7E, false);
CGEventSetFlags(upd, kCGEventFlagMaskControl);
CGEventSetFlags(upu, kCGEventFlagMaskControl);
CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works
CGEventPost(loc, ctrld);
CGEventPost(loc, upd);
usleep(20000);
CGEventPost(loc, upu);
CGEventPost(loc, ctrlu);
CFRelease(ctrld);
CFRelease(ctrlu);
CFRelease(upd);
CFRelease(upu);
CFRelease(src);
}
NSLog(@"Done");
return 0;//NSApplicationMain(argc, argv);
}
But failed.
I tried to use this piece of code to simulate Cmd+Space (0x38 + 0x31 + Command Mask), it succeeded once, I think must be something wrong in my code...
I also ran into this problem. All flags (kCGEventFlagMaskCommand, kCGEventFlagMaskShift) except kCGEventFlagMaskControl worked. I added kCGEventFlagMaskSecondaryFn as written here Simulated key command not working since OS upgrade and now works.