Search code examples
copyswift2nspasteboard

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.


Solution

  • 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.