我正在尝试在 Mac OS 上模拟一些按键。如果按下“h”键(例如,如果用户键入“tigh”,它将变为“ti”),此代码应该通过修改键盘事件删除前一个字符。但是它只适用于某些应用程序;其他人完全拒绝我的活动。这段代码有问题吗?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
CFMachPortRef eventTap;
CGEventMask eventMask;
CFRunLoopSourceRef runLoopSource;
eventMask = ((1 << kCGEventKeyDown) | (1 << kCGEventKeyUp));
eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
eventMask, KeyHandler, NULL);
if (!eventTap) {
fprintf(stderr, "failed to create event tap\n");
exit(1);
}
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, true);
CFRunLoopRun();
}
CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
UniCharCount actualStringLength;
UniCharCount maxStringLength = 1;
UniChar chars[3];
CGEventKeyboardGetUnicodeString(event, maxStringLength, &actualStringLength, chars);
if (chars[0] == 'h') {
chars[0] = '\b';
CGEventKeyboardSetUnicodeString(event, 1, chars);
return event;
}
return event;
}