问题描述
有人在OS X上使用CGEventCreateKeyboardEvent模拟Caps Lock击键有运气吗?基本上,我尝试过字母字符和字母数字字符,但是可以使用Caps Lock.希望我想模拟Caps Lock击键来打开/关闭LED.我不知道我的测试代码有什么问题.有人有经验吗?
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);
}
使用以下命令编译
gcc test.c -framework ApplicationServices
推荐答案
您是否需要实际切换大写锁定状态,还是仅打开/关闭LED足够?如果只是LED,则在以下位置有一些示例代码:
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
请注意,它根本不涉及CGEvent -它使用IOKit魔术来直接弄乱键盘LED.
Note that it doesn't involve CGEvent at all -- it uses IOKit magic to mess with the keyboard LEDs directly.
这篇关于如何在OS X中使用CGEventCreateKeyboardEvent模拟Caps Lock击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!