2

我很难处理自定义键盘事件。我希望能够发送带/不带 kCGEventFlagMask 的任何键,例如 command、alt、ctrl、shift ......

例如,我想发送当前最前面的应用程序,假设它是 TextEdit,组合键 cmd+t,它应该显示字体窗口。

但是目前只有 t 被添加到 TextEdit 的当前文档中。我尝试使用自定义设置 CGEventFlags 发布事件,并在 t 事件周围为 cmd 生成 keyDown 和 keyUp 事件。当我使用 CGEventFlags 集时,免费应用程序 Key Codes 向我显示 cmd+t 已按下,但此组合键未传递给 TextEdit,只有单个 t...

这是我的代码:

...
flags = (flags | kCGEventFlagMaskCommand);
[self writeString:@"" withFlags:flags];
...

(void)writeString:(NSString *)valueToSet withFlags:(int)flags
{
UniChar buffer;
CGEventRef keyEventDown = CGEventCreateKeyboardEvent(NULL, 1, true);
CGEventRef keyEventUp = CGEventCreateKeyboardEvent(NULL, 1, false);
CGEventSetFlags(keyEventDown,0);                
CGEventSetFlags(keyEventUp,0);          
for (int i = 0; i < [valueToSet length]; i++) {
    [valueToSet getCharacters:&buffer range:NSMakeRange(i, 1)];
    CGEventKeyboardSetUnicodeString(keyEventDown, 1, &buffer);
    CGEventSetFlags(keyEventDown,flags);
    CGEventPost(kCGSessionEventTap, keyEventDown);
    CGEventKeyboardSetUnicodeString(keyEventUp, 1, &buffer);
    CGEventSetFlags(keyEventUp,flags);
    CGEventPost(kCGSessionEventTap, keyEventUp);

}
CFRelease(keyEventUp);
CFRelease(keyEventDown);

}

我也很难理解 CGEventTapLocation 的含义。我不知道哪个事件点击最适合我的任务。Quartz Event Reference 中的描述并没有启发我:

kCGHIDEventTap
Specifies that an event tap is placed at the point where HID system events enter the window server.


kCGSessionEventTap
Specifies that an event tap is placed at the point where HID system and remote control events enter a login session.


kCGAnnotatedSessionEventTap
Specifies that an event tap is placed at the point where session events have been annotated to flow to an application.

我看过很多关于该主题的帖子,但没有一个能帮助我解决我的问题......感谢您的帮助!

4

1 回答 1

3

这不是问题的答案,而是我目前通过 AppleScript 的解决方法:

appleScriptString = [NSString stringWithFormat:@"tell application \"System Events\" to key code %d using %@",keyCode, modifierDownString];

我将其提供给该功能:

- (void)runScript:(NSString*)scriptText
{
    NSDictionary *error = nil;
    NSAppleEventDescriptor *appleEventDescriptor;
    NSAppleScript *appleScript;

    appleScript = [[NSAppleScript alloc] initWithSource:scriptText];
    appleEventDescriptor = [appleScript executeAndReturnError:&error];

    [appleScript release];
}
于 2011-10-17T14:39:06.187 回答