CGEventCreateKeyboardEvent和CGEventTapLocation

时间:2011-10-07 17:58:24

标签: macos cocoa cgeventtap

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

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

但目前只有t被添加到TextEdit的当前文档中。我尝试使用自定义集CGEventFlags发布事件,并为t事件周围的cmd生成keyDown和keyUp事件。免费应用程序密钥代码显示我使用CGEventFlags设置时,已按下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.

我看过很多关于这个主题的帖子,但没有一个人帮我解决了我的问题...... 谢谢你的帮助!

1 个答案:

答案 0 :(得分:2)

这不是问题的答案,而是我目前使用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];
}