Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste text from one app to another using Cocoa?

I have read about NSPasteBoard in the Apple documentation, and how it allows for applications to write into the PasteBoard and allow other applications to read that text and use it.

Could someone tell me how to paste text from am application (that sits in the status bar) into a NSTextField that is inside a different application.

What I am trying to do is something similar what Snippet and SnippetsApp do.

If I am completely stupid and missed the obvious in Apple Docs, could you please point me to the right path :)

Thanks!

like image 240
Navi Sidhu Avatar asked Apr 21 '10 06:04

Navi Sidhu


1 Answers

Could someone tell me how to paste text from am application (that sits in the status bar) into a NSTextField that is inside a different application.

Pasting is what happens in the receiving application. Writing to a pasteboard is copying.

Furthermore, you can't assume that the user will want to paste into an NSTextField. It may be an NSTextView, or a textarea in a WebView, or a Carbon EditText or MLTE control, or some other text editor such as a Qt or wxWidgets text editor. They may even be using an app with a list view that lets them paste text directly into it.

So, there's no programmatic way to directly tell an application “here's some text — paste it, please”. You have to copy it to the general pasteboard and then forge an event that should generally cause the frontmost app to paste. Charlie's suggestion of ⌘V is one way, albeit tricky; the Dvorak layout puts V on another key, while the “Dvorak QWERTY ⌘” layout puts V-with-⌘ (as opposed to V-without-⌘) on the same key as QWERTY's V.

To forge that ⌘V event, look into CGEventTap. You'll need to use the CGEventCreateKeyboardEvent function to create the event itself, and since that function takes a key code, you'll need to look up the proper key code for the V part of the ⌘V combination, which will require going through Text Input Source Services or Keyboard Layout Services, depending on the layout.

You might at this point think of using Accessibility to find the Paste menu item in the Edit menu and send it an AXPress message, but “Paste” and “Edit” are only English's words for those concepts; if you did this, your app would not work in any other language. You could go by order (third menu, sixth menu item), but then your app would not work in applications without a File menu, or without a Redo menu item, or with two Undo menu items (Photoshop). Forging a ⌘V event really is the way to go.

like image 99
Peter Hosey Avatar answered Oct 15 '22 09:10

Peter Hosey