Alex Rivera | Logout

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

Asked 2010-04-21T06:25:21.183
9

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!

Edit
Report

2 Answers

9

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 answered 2010-04-22T16:07:27.053

8

Here's some working code to post the ⌘+key event (assuming a known keycode):

// some common keycodes
#define KEY_CODE_x ((CGKeyCode)7)
#define KEY_CODE_c ((CGKeyCode)8)
#define KEY_CODE_v ((CGKeyCode)9)

void DCPostCommandAndKey(CGKeyCode key)
{
    CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);

    CGEventRef keyDown = CGEventCreateKeyboardEvent(source, key, TRUE);
    CGEventSetFlags(keyDown, kCGEventFlagMaskCommand);
    CGEventRef keyUp = CGEventCreateKeyboardEvent(source, key, FALSE);

    CGEventPost(kCGAnnotatedSessionEventTap, keyDown);
    CGEventPost(kCGAnnotatedSessionEventTap, keyUp);

    CFRelease(keyUp);
    CFRelease(keyDown);
    CFRelease(source);  
}
answered 2010-12-02T10:30:38.163

Your Answer