Search code examples
iosswiftkeypress

How simulate keypress using Swift?


How simulate pressing the keyboard button?

I tried:

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)

And:

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

But I got errors:

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

and etc.

How do I use this code?

What kind of framework to connect?

Or how can I do it differently?


Solution

  • CGEventSourceRef only exists on macOS.

    You might have other options to try out. Check out Olaf's answer here.

    Otherwise you'll need to take a step back and figure out how else to test the code behind your UI without involving the keyboard.