Mac OS でいくつかのキーの押下をシミュレートしようとしています。このコードは、'h' キーが押された場合 (たとえば、ユーザーが 'tigh' と入力すると 'ti' になる)、キーボード イベントを変更することにより、前の 1 文字を削除することになっています。ただし、一部のアプリケーションでのみ機能します。他の人は私のイベントを完全に拒否します。このコードに問題はありますか?
- (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;
}