我正在編寫一個應用程序,通過將突出顯示的文本複製到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?可可虛擬擊鍵疼痛
我試過的AppleScript建議用NSAppleScript:
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,但我得到的是嘟嘟聲,和剪貼板內容不變。
我很有智慧 - 任何人都可以啓發我對我失去的東西或指出我對我忽視的東西如此簡單嗎?
不要傳遞'error:nil'。首先,它需要一個指向變量的指針,而不是一個指向對象的指針,所以正確的常量將是'NULL',而不是'nil'。更重要的是,不要阻止框架告訴你出了什麼問題。傳遞一個指向NSError *變量的指針,如果您嘗試執行的操作失敗,則至少記錄錯誤對象。 – 2010-04-19 17:51:25