Aaron
Aaron

Reputation: 1342

Copy Selected Text with Swift

I am writing a popover menu bar app in OS X.

The goal is to copy the selected text of the currently active application (not my popover) into my app so I can use it as a String.

Upvotes: 2

Views: 1686

Answers (2)

Aaron
Aaron

Reputation: 1342

Figured it out!

NOTE: You have to delay the paste function. copyText() needs time to write to the pasteboard.

func copyText() {
    // Clear pasteboard
    pasteBoard.clearContents()

    let src = CGEventSourceCreate(CGEventSourceStateID.HIDSystemState)

    //let cmdd = CGEventCreateKeyboardEvent(src, 0x37, true)
    let cmdu = CGEventCreateKeyboardEvent(src, 0x37, false)

    let c_down = CGEventCreateKeyboardEvent(src, 0x08, true)
    let c_up = CGEventCreateKeyboardEvent(src, 0x08, false)

    // Set Flags
    CGEventSetFlags(c_down, CGEventFlags.MaskCommand)
    CGEventSetFlags(c_up, CGEventFlags.MaskCommand)

    let loc = CGEventTapLocation.CGHIDEventTap

    //CGEventPost(loc, cmdd)
    CGEventPost(loc, c_down)
    CGEventPost(loc, c_up)
    CGEventPost(loc, cmdu)
}


func paste() -> String {
    let lengthOfPasteboard = pasteBoard.pasteboardItems!.count
    print(lengthOfPasteboard)
    var theText = ""
    if lengthOfPasteboard > 0 {
      theText = pasteBoard.pasteboardItems![0].stringForType("public.utf8-plain-text")!
    } else {
      theText = "Nothing Coppied"
    }

    //print(theText)
    return theText
}

I'm calling this from AppDelegate.swift, not the ViewController. So that it will hopefully copy the text before my popover becomes the active/focused window.

Upvotes: 3

Michael
Michael

Reputation: 9044

The NSPasteboard class is used to put/get info on the pasteboard. As I understand it, you want to get the currently selected text in another application into a string in your application. The Accessibility APIs to achieve this.

You can send keys to another application, so you could send Cmd-C to the other application, and then pull the data from the pasteboard. An example of this in obj-c can be found here.

Upvotes: 2

Related Questions