Simulate Keydown on Mac with Cinder


I have a simple use case, I want to detect a Leap Motion gesture then register a key event (only left or right arrows). I need the event to be on fired on the OS level or somehow target keynote specifically. Is Cinder the right tool for this? I have an application set up with Leap Motion working but simulating the keys is giving me some trouble.



Cinder can do anything C++ can do, so it can definitely do this. Normally I would say Cinder could even be a little overkill, but since you’re interfacing with the leap, I think it’s a good fit.

On OSX, the native function you’re going to want to be looking for is CGEventPost. Here is a basic example of pressing, then releasing the ‘s’ key. You’ll need to make sure the window is focused on Keynote, but Cinder should be happy enough to run in the background.

CGKeyCode inputKeyCode = kVK_ANSI_S;            
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

CGEventRef keyDown = CGEventCreateKeyboardEvent(source, inputKeyCode, YES);
CGEventRef keyUp = CGEventCreateKeyboardEvent(source, inputKeyCode, NO);

CGEventPost(kCGAnnotatedSessionEventTap, keyDown);
CGEventPost(kCGAnnotatedSessionEventTap, keyUp);


Let us know how it goes!


Hi Charlie, thanks for your reply.

I am trying this. I am having issues with finding the appropriate includes.

#include “CGRemoteOperation.h” // eliminated some errors
#include “cinder/cocoa/CinderCocoa.h” // seems to have done nothing

“Unknown type name ‘CGEventSourceRef’”
“Use of unknown identifier ‘kCGEventSourceStateCombinedSessionState’”

Do you know what to import by chance?



I do. You’re going to want these two:
#include <CoreGraphics/CGEventSource.h>
#include <Carbon/Carbon.h>

I’ll also whip up a quick block as a proof of concept. Seems like it could be useful.


Thank you so much, got the concept running. Will let you know if everything goes well as I am fleshing it out.


Just pushed a basic header-only block which is hopefully useful enough to expand on. It works well and is surprisingly fun.