2

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.

Aaron
  • 1,312
  • 3
  • 14
  • 25

2 Answers2

3

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.

Aaron
  • 1,312
  • 3
  • 14
  • 25
2

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.

Community
  • 1
  • 1
Michael
  • 8,891
  • 3
  • 29
  • 42
  • That is exactly right, that is what I want to do. But I can't get the Objective-C code to convert. I might need to look for the swift equivalent of CGEventCreateKeyboardEvent. It doesn't like any of the identifiers given in that block of code. – Aaron Jan 19 '16 at 03:34
  • Have a look at http://stackoverflow.com/questions/27484330/simulate-keypress-using-swift - it is doing a similar thing and is written in Swift (although there may still be some differences for Swift 2). There's also similar code at https://github.com/pikajude/Maxxxro/blob/master/Maxxxro/ButtonPusher.swift that you might want to look at. – Michael Jan 19 '16 at 04:11