0
NSPerformService(@"Copy Selected Text", pboard);

- (void)copyText:(NSPasteboard *)pboard userData:(NSString *)userData error:(NSString **)error {
NSString *copiedText = [pboard stringForType:NSStringPboardType];
NSLog('copied text %@', copiedText);
}

The copyText:userData:error: invoked successfully but the copiedText is empty which shouldn't. I do have select some text before I call NSPerformService.

If I invoke my service by select the Service menu, it works properly.

I assume that calling NSPerformService didn't write the selection text into the generalPasteboard.

Lucidus
  • 161
  • 1
  • 5

1 Answers1

0

NSPerformService cannot get selected text automatically. It is meant to enable you to use services without UI (e.g. in a command line tool). You have to specifically put the text you want the service to work on into the pasteboard you provide as a parameter. Of course, for the service "Copy Selected Text", this wouldn't make any sense...

omz
  • 53,243
  • 5
  • 129
  • 141
  • How about [this](http://stackoverflow.com/questions/6118435/how-to-save-off-the-pasteboard-contents-first-and-restore-them-afterward). I came up with the idea to simulate CMD+C to copy the selection into pasteboard. But I don't want to override user's original pasteboard data. – Lucidus May 25 '11 at 02:25
  • What do you actually want to achieve? Do you want to use services within your own app or is the goal to copy text from another app (any app? specific app?) – omz May 25 '11 at 13:58
  • Copying selected text from another app could either be achieved by storing the current pasteboard content and then simulating Cmd+C (have a look at the CGEvent* APIs) – or, if the target app supports it, by using the Accessibility (AX) APIs. The latter is a bit more elegant and doesn't require to use the pasteboard at all, but not all apps support it and it requires access for assistive devices to be turned on in the system preferences. – omz May 25 '11 at 14:03