How to simulate Caps Lock keystroke with CGEventCreateKeyboardEvent in OS X
Has anyone had any luck simulating Caps Lock keystroke with CGEventCreateKeyboardEvent on OS X? Basically I have tried alphabetic character and alphanumeric character okay but Caps Lock. Hopefully, I would like to simulate Caps Lock keystroke to trun on/off the LED. I don't know what problem is for my test code. Has anyone had experinces 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, CapsLockDo开发者_如何学编程wn); /* doesn't work */
//CGEventPostToPSN(&psn, CapsLockUp);
CFRelease(CapsLockUp);
CFRelease(CapsLockDown);
CFRelease(source);
}
Compile with below command
gcc test.c -framework ApplicationServices
Do you need to actually toggle the caps lock state, or is merely turning the LED on/off sufficient? If it's just the LEDs, there's some sample code at:
https://github.com/mikeash/mikeash.com-svn/blob/master/CPUFlash/keyboard_leds.c
Note that it doesn't involve CGEvent at all -- it uses IOKit magic to mess with the keyboard LEDs directly.
Haha! This might just be a classic.. Your code exits because it was really able to do anything at all. Add some sleep(seconds)
's here and there. Also try putting a small delay (usleep(microseconds)
) in between the down and up events.
精彩评论