我试图模仿Mac OS上的一些按键。 此代码应该删除一个前一个字符,如果“H”键被按下时(例如,如果用户输入“tigh”,它会成为“钛”)通过修改键盘事件。 然而,它仅适用于某些应用程序; 别人完全拒绝我的事件。 是否有与此代码什么问题?
- (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;
}