2015-04-05 55 views
0

我想選定的文本複製到剪貼板中使用此代碼Cocoa應用程序:複製選擇在最前面的應用程序使用AppleScript

NSString * copyStr [email protected]"tell application \"System Events\" to key code 8 using command down"; 
copyScript = [[NSAppleScript alloc] initWithSource:copyStr]; 
NSAppleEventDescriptor *aDescriptor = [copyScript executeAndReturnError:&errorDict]; 

遺憾的是沒有任何反應。 你知道可能是什麼問題嗎?

+1

沒有防彈方式強制另一個應用程序複製其選擇。請考慮實施[服務](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/SysServices/introduction.html),而不是嘗試這樣做。如果你堅持這樣做,因爲你已經在編寫Objective-C,所以不要使用AppleScript。使用[Quartz Event Services](https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/)發佈事件。搜索「CGEventPost()」或「CGEventPostToPSN()」。 – 2015-04-05 19:58:59

+0

感謝您的評論。我有一個CGEvents的工作解決方案,但這不適用於沙盒... – 2015-04-06 07:05:06

回答

1

捕獲目標應用程序選擇這種方式,如果它接受命令。

您需要使其成爲活動應用程序。 由於您正在使用這樣的複製功能,因此您並不需要添加進程tell block。但是有一些GUI命令不需要使目標應用程序處於活動狀態,只需使用tell application process塊。 海事組織它是用它很好的做法..

所以,如果你決定或者需要使用進程名在tell application process你也可以使用的NSString stringWithFormat:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 

    [self runApplescriptCopy:@"Safari"]; 

} 



-(void)runApplescriptCopy:(NSString*) processName{ 


    NSDictionary * errorDict; 
    NSString * copyStr = [NSString stringWithFormat:@"tell application \"%@\" to activate \n tell application \"System Events\" to tell application process \"%@\" to key code 8 using command down",processName ,processName ]; 
    NSAppleScript * copyScript = [[NSAppleScript alloc] initWithSource:copyStr]; 
    NSAppleEventDescriptor *aDescriptor = [copyScript executeAndReturnError:&errorDict]; 


} 
0

您應該真的在程序塊中添加進程名稱。 (這是寫出來的)

tell app "processname" to activate 
tell app "System Events" 
    tell app process "processname" 
     key code 8 using command down 
    end tell 
end tell 
相關問題