我正在编写一个应用程序,通过将突出显示的文本复制到 NSPasteboard 的 generalPasteboard 中来响应热键。在这里寻找发送虚拟击键的解决方案后,我发现了这个:如何在objective-c中向活动应用程序发送“Cmd-C”击键,或者告诉应用程序执行复制操作?
我尝试了使用 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);
以上应该发送击键命令+ c,但我得到的只是哔声,粘贴板内容没有改变。
我束手无策 - 任何人都可以启发我了解我缺少什么或指出我忽略了什么如此简单的事情吗?