2

我需要同时模拟 CMD+Option+D 按键。我已经做了各种寻找,到目前为止我见过的最好的方法是这样做:

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);

但是,这样做不会像我使用键盘时那样切换扩展坞?为什么是这样?我究竟做错了什么?我导入了 Carbon.h,所以看起来这应该可以吗?

4

1 回答 1

2

你试过这个吗?

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

我认为您必须为 D 事件设置命令备用(选项键)标志。

于 2013-03-04T17:20:46.087 回答