在某些应用程序中,CGEventPost不支持退格字符

时间:2012-05-28 07:43:14

标签: objective-c cocoa cgeventtap

(这个问题类似于我最近发布的问题here,除了现在我正在使用CGEventPost来模拟更多的击键而不是修改当前事件)

每次按下'h'按钮时,下面的代码都可以插入一个'a'字符,它适用于所有应用程序。

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') {

        CGEventRef keyEventDown = CGEventCreateKeyboardEvent( NULL, 1, true);
        CGEventRef keyEventUp = CGEventCreateKeyboardEvent( NULL, 1, false);

        chars[0] = 'a';
        CGEventKeyboardSetUnicodeString(keyEventDown, 1, chars);
        CGEventKeyboardSetUnicodeString(keyEventUp, 1, chars);
        CGEventSetIntegerValueField(keyEventDown, kCGKeyboardEventKeycode, 0); // 0 is key code of 'a' button
        CGEventSetIntegerValueField(keyEventUp, kCGKeyboardEventKeycode, 0);

        CGEventPost(kCGSessionEventTap, keyEventDown);
        CGEventPost(kCGSessionEventTap, keyEventUp);
        return NULL;
    }

    return event;
}

如果我用退格符替换'a',某些应用程序(例如Mac上的Microsoft Excel ...)就不再识别它了。你知道为什么吗?

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') {

        CGEventRef keyEventDown = CGEventCreateKeyboardEvent( NULL, 1, true);
        CGEventRef keyEventUp = CGEventCreateKeyboardEvent( NULL, 1, false);

        chars[0] = '\b';
        CGEventKeyboardSetUnicodeString(keyEventDown, 1, chars);
        CGEventKeyboardSetUnicodeString(keyEventUp, 1, chars);
        CGEventSetIntegerValueField(keyEventDown, kCGKeyboardEventKeycode, 51);
        CGEventSetIntegerValueField(keyEventUp, kCGKeyboardEventKeycode, 51);

        CGEventPost(kCGSessionEventTap, keyEventDown);
        CGEventPost(kCGSessionEventTap, keyEventUp);
        return NULL;       
    }

    return event;
}

2 个答案:

答案 0 :(得分:0)

“\ b”转义序列产生ASCII 0x08。在我的测试中,当我按下删除键(即退格键)时生成的事件是ASCII 0x7f。

通常,这似乎是用于弄清楚如何模拟事件的明显技术。使用捕获它并转储其细节的工具执行该事件。

答案 1 :(得分:0)

想出来。如果我删除代码为事件设置unicode字符串,一切都会正常工作:

chars[0] = '\b';
CGEventKeyboardSetUnicodeString(keyEventDown, 1, chars);
CGEventKeyboardSetUnicodeString(keyEventUp, 1, chars);

但是,我不知道为什么在Mac OS上某些特定应用程序会发生这种情况。