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