使用 applescript 在最前面的应用程序中复制选择

Copy selection in frontmost app using applescript

我正在尝试使用以下代码将所选文本复制到 Cocoa 应用程序中的剪贴板:

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

不幸的是,什么也没发生。 您知道可能是什么问题吗?

您真的应该在块中添加进程名称。 (这是即时写出来的)

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

以这种方式捕获目标应用程序选择以及它是否接受命令。

您需要将其设为活动应用。 因为您正在使用这样的复制功能,所以您实际上不需要添加进程告诉块。但是有一些 GUI 命令不需要使目标应用程序处于活动状态,只需使用 tell application process 块即可。 imo 使用它是一种很好的做法..

因此,如果您决定或需要在 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];


}