cocoaapplescriptnsapplescript

Copy selection in frontmost app using applescript


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?


Solution

  • 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];
    
    
    }