我很难处理自定义键盘事件。我希望能够发送带有/不带有命令,alt,ctrl,shift的kCGEventFlagMasks的任何键。
例如我想发送当前最前端的应用程序,假设它是TextEdit,组合键cmd + t,它应该显示字体窗口。
但是目前只有t被添加到TextEdit的当前文档中。我尝试使用自定义设置CGEventFlags发布事件,或者在t事件周围为cmd生成keyDown和keyUp事件。当我使用CGEventFlags设置时,免费的应用程序“键代码”向我显示了cmd + t已被按下,但是此键组合未传递到TextEdit,仅传递了一个。
这是我的代码:
...
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.
我看过很多关于该主题的帖子,但是它们都没有帮助我解决问题...
谢谢你的帮助!
最佳答案
那不是问题的答案,而是我目前通过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];
}
关于macos - CGEventCreateKeyboardEvent和CGEventTapLocation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7691044/