2014-12-02 52 views
4

我正在嘗試使用CGEventCreateKeyboardEventCGEventPost發送系統級鍵盤快捷鍵(如control-F4)的鍵擊,但未成功。使用CGPostKeyboardEvent發送此類擊鍵工作得很好,但該方法已過時,我正在尋找替代方法。如何使CGEventCreateKeyboardEvent和CGEventPost組合等同於CGPostKeyboardEvent?

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

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

有人會告訴我什麼是錯的或我應該讀入的東西嗎?我擔心這種CGPostKeyboardEvent發佈全系統快捷方式的能力是一個貶損的原因。任何輸入將不勝感激!

回答

3

我通過stackoverflow得到了一個答案日本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; 
}