如何使用Swift模拟按键?

时间:2019-02-20 19:36:43

标签: ios swift keypress

如何模拟按下键盘按钮?

我尝试过:

let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)

let cmdd = CGEvent(keyboardEventSource: src, virtualKey: 0x38, keyDown: true)
let cmdu = CGEvent(keyboardEventSource: src, virtualKey: 0x38, keyDown: false)
let spcd = CGEvent(keyboardEventSource: src, virtualKey: 0x31, keyDown: true)
let spcu = CGEvent(keyboardEventSource: src, virtualKey: 0x31, keyDown: false)

spcd?.flags = CGEventFlags.maskCommand;

let loc = CGEventTapLocation.cghidEventTap

cmdd?.post(tap: loc)
spcd?.post(tap: loc)
spcu?.post(tap: loc)
cmdu?.post(tap: loc)

并且:

let controlKeyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: CGKeyCode(kVK_Control), keyDown: true)
   controlKeyDownEvent?.flags = CGEventFlags.maskCommand
   controlKeyDownEvent?.post(tap: CGEventTapLocation.cghidEventTap)

但是我遇到了错误:

Use of unresolved identifier 'CGEvent' 
Use of unresolved identifier 'CGKeyCode' 
Use of unresolved identifier 'kVK_Control' 

如何使用此代码?

要连接哪种框架?

或者我该怎么做?

1 个答案:

答案 0 :(得分:0)

CGEventSourceRef only exists on macOS

您可能还有其他选择可以尝试。 Check out Olaf's answer here

否则,您需要退后一步,弄清楚如何 else 在不涉及键盘的情况下测试UI背后的代码。