使用Swift复制选定的文本 [英] Copy Selected Text with Swift

查看:76
本文介绍了使用Swift复制选定的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在OS X中编写一个弹出菜单栏应用程序.

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.

推荐答案

想通了!

注意:您必须延迟粘贴功能.copyText()需要一些时间才能写入粘贴板.

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
}

我从AppDelegate.swift而不是ViewController调用它.这样一来,它有望在我的弹出窗口成为活动/焦点窗口之前复制文本.

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.

这篇关于使用Swift复制选定的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆