Cocoa Swift:单击按钮时模拟按键

时间:2017-11-27 04:12:51

标签: swift macos cocoa macos-high-sierra

我尝试通过点击我的应用上的按钮来模拟按键。我已经搜索了stackoverflow,并且有一些例子,但它们似乎都不适合我。我可以在控制台中看到print语句,但是当我切换到文本编辑器时没有按下任何字符。这就是我所拥有的:

@IBAction func buttonClicked(_ sender: Any) {
    // Set delay to allow me to switch to a text editor
    let when = DispatchTime.now() + 2
    DispatchQueue.main.asyncAfter(deadline: when) {
        print("pressing keyboard button")
        self.keyboardKeyDown(key: 6)
        self.keyboardKeyUp(key: 6)
    }
}

func keyboardKeyDown(key: CGKeyCode) {
    let source = CGEventSource(stateID: .hidSystemState)
    let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: true)
    event?.post(tap: .cghidEventTap)
}

func keyboardKeyUp(key: CGKeyCode) {
    let source = CGEventSource(stateID: .hidSystemState)
    let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: false)
    event?.post(tap: .cghidEventTap)
}

1 个答案:

答案 0 :(得分:-1)

发现这个SO答案。似乎与你所做的非常相似 Simulate keypress using Swift

您是否尝试在应用内打开文本字段,以查看是否在此处收到了按键。