1

我正在尝试在 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;
}
4

1 回答 1

2

一些应用程序根据事件 ( CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode)) 中的键代码而不是事件的UnicodeString.

也就是说,您需要将事件的kCGKeyboardEventKeycode值从“h”提供的4更新为51或退格键 ( 0x33 )。

于 2012-05-24T17:54:34.347 回答