gpt4 book ai didi

objective-c - cocoa 虚拟按键痛

转载 作者:行者123 更新时间:2023-12-03 17:08:10 25 4
gpt4 key购买 nike

我正在编写一个应用程序,通过将突出显示的文本复制到 NSPasteboard 的 GeneralPasteboard 中来响应热键。在这里寻找发送虚拟击键的解决方案后,我发现了这个:How to send a "Cmd-C" keystroke to the active application in objective-c, or tell the application to do a copy operation?

我尝试了 NSAppleScript 建议的 applescript:

NSLog(@"Hotkey Pressed");
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];

NSAppleScript *playScript;
playScript = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to keystroke \"c\" using command down"];

if([playScript isCompiled] == NO){
[playScript compileAndReturnError:nil];
}

id exerror = [playScript executeAndReturnError:nil];

if(exerror == nil){
NSLog(@"Script Failed");
}

它有效,但仅在我第一次按下热键时有效。随后的每次点击都不会抓取突出显示的文本。再次运行脚本之前,generalPasteboard 仍然包含相同的内容。在运行代码之前清除 GeneralPasteboard 是没有用的,因为这样代码在尝试读取粘贴板内容时会失败。这是日志:

 Pastify[16929:a0b] woooooooo! I'm being CALLED
Pastify[16929:a0b] Hotkey Pressed
Pastify[16929:a0b] Error loading /Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: dlopen(/Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types, 262): no suitable image found. Did find:
/Library/ScriptingAdditions/Adobe Unit Types.osax/Contents/MacOS/Adobe Unit Types: no matching architecture in universal wrapper
Pastify: OpenScripting.framework - scripting addition "/Library/ScriptingAdditions/Adobe Unit Types.osax" declares no loadable handlers.
Pastify[16929:a0b] Size of copiedItems: 1
Pastify[16929:a0b] Content of paste: 2010-04-19 03:41:04.355 Pastify[16929:a0b] woooooooo! I'm being CALLED
Pastify[16929:a0b] Hotkey Pressed
Pastify[16929:a0b] Size of copiedItems: 1
Pastify[16929:a0b] Content of paste: 2010-04-19 03:41:04.355 Pastify[16929:a0b] woooooooo! I'm being CALLED
Pastify[16929:a0b] Hotkey Pressed
Pastify[16929:a0b] Size of copiedItems: 1
Pastify[16929:a0b] Content of paste: 2010-04-19 03:41:04.355 Pastify[16929:a0b] woooooooo! I'm being CALLED

所以我尝试了下一个建议的解决方案:

 CFRelease(CGEventCreate(NULL));

CGEventRef event1, event2, event3, event4;
event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)50, true);
event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)8, true);
event3 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)8, false);
event4 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)50, false);

CGEventPost(kCGHIDEventTap, event1);
CGEventPost(kCGHIDEventTap, event2);
CGEventPost(kCGHIDEventTap, event3);
CGEventPost(kCGHIDEventTap, event4);

上面应该发送击键 Command + c,但我得到的只是一声蜂鸣声,并且粘贴板内容没有改变。

我束手无策 - 谁能启发我,让我明白我错过了什么,或者指出我在如此简单的事情上忽略了什么?

最佳答案

您是否有无法为此使用服务的原因?

如果您确实想通过合成事件来做到这一点,那么最好的选择是发布修改后的键盘事件而不是向下/向上 - 请参阅此问题以了解更多详细信息。

Simulating key press events in Mac OS X

如果这不起作用,那么,你知道在哪里可以找到我:-)

关于objective-c - cocoa 虚拟按键痛,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2666154/

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