Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating key press events in Mac OS X

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?

like image 665
Thomi Avatar asked Mar 04 '10 14:03

Thomi


1 Answers

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).

like image 121
Tyler Liu Avatar answered Sep 19 '22 13:09

Tyler Liu