I'm writing an app where I need to simulate key press events on a Mac, given a code that represents each key. It seems I need to use the CGEventCreateKeyboardEvent
function to create the event. The problem is that this function needs a Mac keycode, and what I have is a code that represents the specific key. So, for example, I receive:
KEY_CODE_SHIFT
or KEY_CODE_A
- these are both numeric constants defined somewhere.
I need to take these constants and turn them into CGKeyCode
values.
My current attempt uses code similar to this SO question. The problem is that it only works for printable characters. If all else fails, I'm not above hard coding the conversion, but that would mean that I'd need a table of possible CGKeyCode values, which I have not yet been able to find.
Any ideas?
Just in case some one needs a Swift version:
XCode 7.3 and Swift 2.2:
let event1 = CGEventCreateKeyboardEvent(nil, 0x09, true); // cmd-v down
CGEventSetFlags(event1, CGEventFlags.MaskCommand);
CGEventPost(CGEventTapLocation.CGHIDEventTap, event1);
let event2 = CGEventCreateKeyboardEvent(nil, 0x09, false); // cmd-v up
CGEventSetFlags(event2, CGEventFlags.MaskCommand);
CGEventPost(CGEventTapLocation.CGHIDEventTap, event2);
Code above simulates CMD-V pressed then released(AKA: paste).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With