How to obtain the selected text from another application?

前端 未结 2 1714
粉色の甜心
粉色の甜心 2020-12-10 08:25

I will soon be working on an application which needs to get the currently selected text in the frontmost application window, be it Safari, Pages, TextEdit, Word, etc., and d

2条回答
  •  没有蜡笔的小新
    2020-12-10 08:47

    If you don't need selected text very frequently, you can programmatically press Command+C, then get the selected text from clipboard. But during my test, this is only works if you turn off App Sandbox (can't submit to Mac App Store).

    Here is the Swift 3 code:

         func performGlobalCopyShortcut() {
    
            func keyEvents(forPressAndReleaseVirtualKey virtualKey: Int) -> [CGEvent] {
                let eventSource = CGEventSource(stateID: .hidSystemState)
                return [
                    CGEvent(keyboardEventSource: eventSource, virtualKey: CGKeyCode(virtualKey), keyDown: true)!,
                    CGEvent(keyboardEventSource: eventSource, virtualKey: CGKeyCode(virtualKey), keyDown: false)!,
                ]
            }
    
            let tapLocation = CGEventTapLocation.cghidEventTap
            let events = keyEvents(forPressAndReleaseVirtualKey: kVK_ANSI_C)
    
            events.forEach {
                $0.flags = .maskCommand
                $0.post(tap: tapLocation)
            }
        }
    
        performGlobalCopyShortcut()
    
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { // wait 0.05s for copy.
            let clipboardText = NSPasteboard.general().readObjects(forClasses: [NSString.self], options: nil)?.first as? String ?? ""
            print(clipboardText)
        }
    

提交回复
热议问题