0

I am trying to copy selected text to the clipboard in a Cocoa application using this code:

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

Unfortunately nothing happens. Do you know what can be the issue?

AP.
  • 5,205
  • 7
  • 50
  • 94
  • 1
    There is no bulletproof way to force another application to copy its selection. Please consider implementing a [Service](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/SysServices/introduction.html) instead of trying to do this. If you insist on doing this, since you're already writing Objective-C, don't use AppleScript. Use [Quartz Event Services](https://developer.apple.com/library/mac/documentation/Carbon/Reference/QuartzEventServicesRef/) to post the events. Search SO for `CGEventPost()` or `CGEventPostToPSN()`. – Ken Thomases Apr 05 '15 at 19:58
  • Thanks for your comment. I have a working solution with CGEvents but this is not allowed with the sandbox... – AP. Apr 06 '15 at 07:05

2 Answers2

1

To capture the target applications selection this way and if it accepts the command.

You need to make it the Active App. Because you are using the copy function like this you do not really need to add the process tell block. But there are some GUI commands that you do not need to make the target app active and just use a tell application process block. imo it is good practice to use it..

So if you do decide or need to use the process name in a tell application process you can also use 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];


}
markhunte
  • 6,805
  • 2
  • 25
  • 44
0

You should really add the process name in the block. (This is written out on the fly)

tell app "processname" to activate
tell app  "System Events"
    tell app process "processname"
         key code 8 using command down
    end tell
end tell
markhunte
  • 6,805
  • 2
  • 25
  • 44
McUsr
  • 1,400
  • 13
  • 10