How to simulate ctrl+up in Mac OSX?

213 Views Asked by At

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...

2

There are 2 best solutions below

0
On

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.

CGEventSetFlags(upd, kCGEventFlagMaskControl | kCGEventFlagMaskSecondaryFn);
CGEventSetFlags(upu, kCGEventFlagMaskControl | kCGEventFlagMaskSecondaryFn);
0
On

Ahhh, I already got it, open mission control is not that complex, just std::system("open /System/Applications/Mission\\ Control.app"); is enough.

But still hard to understand why ctrl+up why not work