I want to realize what I could do with CGPostKeyboardEvent with CGEventCreateKeyboardEvent and CGEventPost

Asked 2 years ago, Updated 2 years ago, 120 views

I'm doing OSX programming and I want to generate key sequences for keyboard shortcuts like Control-F4, but using CGEventCreateKeyboardEvent and CGEventPost doesn't work, and it worked well when I used CGPostKeyboardEvent.However, CGPostKeyboardEvent has become deprecated, so I am looking for another way.

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

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

I would appreciate it if you could let me know how I can run keyboard shortcuts in apps like CGPostKeyboardEvent.I don't know why CGPostKeyboardEvent has become deprecated...

macos objective-c quartz

2022-09-30 20:17

1 Answers

For example, I think you should do the following:

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

int main(intargc, const char*argv[]){
    @autoreleasepool{
        CGEventSourceRefsource=CGEventSourceCreate(kCGEventSourceStateHIDSsystemState);

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

        CGEventPost (location, f4);

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


2022-09-30 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.