如何使CGEventCreateKeyboardEvent和CGEventPost组合等效于CGPostKeyboardEvent?

时间:2014-12-02 21:16:37

标签: objective-c macos quartz-graphics

我正在尝试使用CGEventCreateKeyboardEventCGEventPost为系统范围的键盘快捷键(如control-F4)发送击键但不成功。使用CGPostKeyboardEvent发送这样的击键工作得很好,但该方法已被弃用,我正在寻找替代方案。

CGPostKeyboardEvent((CGCharCode)0, (CGKeyCode)118/*F4*/, true); // worked

CGEventPost(kCGHIDEventTap, CGEventCreateKeyboardEvent(NULL, (CGKeyCode)118/*F4*/, true)); // doesn't work

有人会告诉我有什么问题或者我应该读些什么吗?我担心CGPostKeyboardEvent发布系统范围快捷方式的这种能力是弃用的原因。任何意见都将不胜感激!

1 个答案:

答案 0 :(得分:3)

我通过stackoverflow Japan http://goo.gl/nACVPz得到了答案,并确认以下代码有效!

#import <Foundation/Foundation.h>
#import <Carbon/Carbon.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);

        CGEventRef f4 = CGEventCreateKeyboardEvent(source, kVK_F4, true);
        CGEventSetFlags(f4, kCGEventFlagMaskControl);
        CGEventTapLocation location = kCGHIDEventTap;

        CGEventPost(location, f4);

        CFRelease(f4);
        CFRelease(source);
    }
    return 0;
}