2

This question is a follow up from a very old post:

CGEventPost - hold a key (shift)

I am building a SwiftUI virtual keyboard. Like a real keyboard, I have UIButtons that resemble the hardware buttons ( key a, s, d, etc ) which the user can click with their mouse. The user can also toggle to keep a button pressed.

I can send keyDown events using a function below, but an unable to keep a keyboard key held down. Inferring that my users want to hold every button until released, how would I send a CGEvent that would tell the macOS that the key with keyCode == a is being held by the user?

private func pressButton(_ keyCode: UInt16) {
    // create a key down event
    let eventDown = CGEvent(keyboardEventSource: nil, virtualKey: keyCode, keyDown: true)
    // post the key down event
    eventDown?.post(tap: .cghidEventTap)
}

I tried intentionally only setting the keyDown event without the keyUp event ( as seen in the above function ), but I get an equivalent of a button press as opposed to hold. I also tried to use timers to fire the pressButton method periodically to keep sending button down events, but ran into the issue of "the events are being sent too fast or too slow", in comparison what would happen if i were to hold that specific button on my keyboard.

A useful thread: Simulate keypress using Swift

angryip
  • 2,140
  • 5
  • 33
  • 67

0 Answers0