0

(这个问题与我最近在这里发布的问题相似,只是现在我使用 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;
}
4

2 回答 2

1

弄清楚了。如果我删除代码为事件设置 unicode 字符串,一切都会正常工作:

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

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

于 2012-06-05T05:43:00.830 回答
0

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

一般来说,这似乎是用于确定如何模拟事件的显而易见的技术。使用捕获并转储其细节的工具执行该事件。

于 2012-05-28T08:35:57.643 回答