2015-04-05 56 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 
相关问题