How to simulate Caps Lock keystroke with CGEventCreateKeyboardEvent in OS X

扶醉桌前 提交于 2019-12-06 10:29:47

问题


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, CapsLockDown); /* doesn't work */
    //CGEventPostToPSN(&psn, CapsLockUp);

    CFRelease(CapsLockUp);
    CFRelease(CapsLockDown);
    CFRelease(source);
}

Compile with below command

    gcc test.c -framework ApplicationServices

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7265907/how-to-simulate-caps-lock-keystroke-with-cgeventcreatekeyboardevent-in-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!