How to simulate a Caps Lock keypress using CGEventCreateKeyboardEvent in OS X

Did anyone manage to simulate a Caps Lock key press using CGEventCreateKeyboardEvent on OS X? Mostly I tried an alphabetic character and an alphanumeric character, but Caps Lock. I hope I would like to simulate pressing the Caps Lock key to turn on / off the LED. I don't know what the problem is for my test code. Has anyone had experience for this?

#include <stdio.h> #include <ApplicationServices/ApplicationServices.h> main() { bool wasCapsLockDown = CGEventSourceKeyState(kCGEventSourceStateHIDSystemState, 57); if (wasCapsLockDown) printf("On\n"); else printf("Off\n"); ProcessSerialNumber psn; GetFrontProcess(&psn); CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);//CGEventSourceCreate(kCGEventSourceStateCombinedSessionState); CGEventRef CapsLockDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)57, true); //CGEventFlags modifiers = 0; //modifiers |= kCGEventFlagMaskAlphaShift; //CGEventSetFlags(CapsLockDown, modifiers); CGEventRef CapsLockUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)57, false); // simulate capslock down CGEventPost(kCGHIDEventTap, CapsLockDown); // simulate capslock up CGEventPost(kCGHIDEventTap, CapsLockUp); //CGEventPost(kCGAnnotatedSessionEventTap, CapsLockDown); /* doesn't work */ //CGEventPost(kCGAnnotatedSessionEventTap, CapsLockUp); //CGEventPost(kCGSessionEventTap, CapsLockDown); /* doesn't work */ //CGEventPost(kCGSessionEventTap, CapsLockUp); //CGEventPostToPSN(&psn, CapsLockDown); /* doesn't work */ //CGEventPostToPSN(&psn, CapsLockUp); CFRelease(CapsLockUp); CFRelease(CapsLockDown); CFRelease(source); } 

Compile the command below

  gcc test.c -framework ApplicationServices 
+3
source share
2 answers

Do you need to actually switch the cap lock state or just turn the LED on or off? If these are just LEDs, there is an example code:

https://github.com/mikeash/mikeash.com-svn/blob/master/CPUFlash/keyboard_leds.c

Note that it is not affiliated with CGEvent at all - it uses IOKit magic to mess with the keyboard LEDs.

+1
source

Haha It may just be a classic. Your code exits because it is really capable of doing anything at all. Add some sleep(seconds) here and there. Also try putting a slight delay ( usleep(microseconds) ) between the down and up events.

0
source

All Articles