Simulating keyboard events in OSX

Guides | Tutorial By 3 years ago

I’m currently writing a program which takes input and simulates it back out as keyboard presses.

It’s quite easy, and can be done like so: (this simulates Command-C, a copy shortcut)

A list of character codes for each keyboard key can be found here

const CGKeyCode keyCode = 8;

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef eventDown = CGEventCreateKeyboardEvent(source, keyCode, YES);
CGEventSetFlags(eventDown, kCGEventFlagMaskCommand);
CGEventRef eventUp = CGEventCreateKeyboardEvent(source, keyCode, NO);

CGEventPost(kCGSessionEventTap, eventDown);

//	Keep it down for a bit

CGEventPost(kCGSessionEventTap, eventUp);