CMD+Option+D simulation in Cocoa

2019-07-20 11:19发布

I need to simulate a CMD+Option+D key press simultaneously. I've done all kind of looking and the best way so far I've seen is to do this:

CGEventSourceRef src =
    CGEventSourceCreate(kCGEventSourceStateHIDSystemState);

    CGEventRef cmdd = CGEventCreateKeyboardEvent(src, kVK_Command, true);
    CGEventRef cmdu = CGEventCreateKeyboardEvent(src, kVK_Command, false);
    CGEventRef optd = CGEventCreateKeyboardEvent(src, kVK_Option, true);
    CGEventRef optu = CGEventCreateKeyboardEvent(src, kVK_Option, false);
    CGEventRef dd = CGEventCreateKeyboardEvent(src, kVK_ANSI_D, true);
    CGEventRef du = CGEventCreateKeyboardEvent(src, kVK_ANSI_D, false);

    CGEventSetFlags(dd, kCGEventFlagMaskCommand); //NO idea why this is here.
    CGEventSetFlags(du, kCGEventFlagMaskCommand); //NO idea why this is here.


    CGEventTapLocation loc = kCGHIDEventTap; // kCGSessionEventTap also works
    CGEventPost(loc, cmdd); //Cmd down
    CGEventPost(loc, optd); //Option down
    CGEventPost(loc, dd);   //D down
    CGEventPost(loc, cmdu); //Cmd up
    CGEventPost(loc, optu); //Option up
    CGEventPost(loc, du);   //D up

    CFRelease(cmdd);
    CFRelease(cmdu);
    CFRelease(optd);
    CFRelease(optu);
    CFRelease(dd);
    CFRelease(du);
    CFRelease(src);

However, doing this does not toggle the dock like it does when I use my keyboard? Why is this? What am I doing wrong? I imported Carbon.h, so it seems like this should work?

1条回答
聊天终结者
2楼-- · 2019-07-20 11:51

Did you try this?

// as before ...
CGEventSetFlags(dd, kCGEventFlagMaskCommand ^ kCGEventFlagMaskAlternate); 
CGEventSetFlags(du, kCGEventFlagMaskCommand ^ kCGEventFlagMaskAlternate);
// continues...

I think you have to set both the command and alternate (option key) flags for the D event.

查看更多
登录 后发表回答