How to make CGEventCreateKeyboardEvent and CGEventPost combos equivalent to CGPostKeyboardEvent?

I am trying to send keystrokes for a public keyboard shortcut (e.g. control-F4) using CGEventCreateKeyboardEventand CGEventPost, but without succeeding. Sending such keystrokes with help CGPostKeyboardEventworked just fine, but the method has become deprecated, and I'm looking for an alternative.

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

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

Will someone tell me what is wrong or something that I should read? I am afraid that this ability CGPostKeyboardEventto issue a system-wide shortcut is causing obsolescence. Any input would be appreciated!

+4
source share
1 answer

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;
}
+3

All Articles