Trigger HID event (Keypress)

hello

I am building a quick app to translate MIDI commands to keypresses for controlling powerpoint with midi. I can’t for the life of me find any way to trigger a keypress in juce. I found an old post in the forum but it wasn’t very clear and just sort of petered out without being answered.

any ideas?

No way to do it in JUCE, you will need platform specific code:

mac:

	static CGEventSourceRef source = NULL;
	
	if (!source)
		source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
	
	CGKeyCode virtualKey = (CGKeyCode) (keyPress & 0x0000FFFF);
	
	CGEventRef keyDn = CGEventCreateKeyboardEvent(source, virtualKey, true);
	CGEventRef keyUp = CGEventCreateKeyboardEvent(source, virtualKey, false);
	
	uint32_t flags = 0;
		
	CGEventSetFlags(keyDn, (CGEventFlags)flags);
	CGEventSetFlags(keyUp, (CGEventFlags)flags);
	
	CGEventPost(kCGAnnotatedSessionEventTap, keyDn);
	CGEventPost(kCGAnnotatedSessionEventTap, keyUp);
	
	CFRelease(keyDn);
	CFRelease(keyUp);

win:

			INPUT input;
			memset(&input, 0, sizeof(input));
			input.type = INPUT_KEYBOARD;
			input.ki.wVk = key;
			input.ki.wScan = MapVirtualKey(input.ki.wVk, MAPVK_VK_TO_VSC);
			input.ki.dwFlags = type;
			keybd_event(key, MapVirtualKey(key, 0), type, 0);

2 Likes

thanks buddy ill give that a whirl. should always be on Mac this one.

hummm maybe im being dim. when I try and

#import <ApplicationServices/ApplicationServices.h>

to get access to CGEvents I get a load of errors. any ideas?

It’s probably Object C header. Make sure you are using a .mm file and include any system headers before the juce headers.