CMD+Option+D simulation in Cocoa

大憨熊 提交于 2019-12-13 15:29:39

问题


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:


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.



来源:https://stackoverflow.com/questions/15206825/cmdoptiond-simulation-in-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!