gpt4 book ai didi

macos - CGEventCreateKeyboardEvent 和 CGEventTapLocation

转载 作者:行者123 更新时间:2023-12-03 16:32:55 26 4
gpt4 key购买 nike

我在处理自定义键盘事件时遇到了困难。我希望能够发送带有/不带 kCGEventFlagMasks 的任何键,例如 command、alt、ctrl、shift...

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

但目前仅将t添加到TextEdit的当前文档中。我尝试使用自定义设置 CGEventFlags 发布事件,并围绕 t 事件为 cmd 生成 keyDown 和 keyUp 事件。免费应用程序 Key Codes 向我显示,当我使用 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.

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

最佳答案

这不是问题的答案,而是我当前通过 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com