Search code examples
swiftmacoscocoakeypress

Implementation key press in Swift


I'm writing an application that will use your's phone as touchpad and simulate different touchpad's gestures by Swift code on Mac. But when I've tried to implement swiping between workspaces (same as three fingers swipe touchpad) due to it is possible to invoke with <kbd>control + arrow</kbd>, I faced with problem of invoking key press.

I've looked up to this discussion and wrote it like

func rightScreen() {
    let key = CGEvent(keyboardEventSource: nil, virtualKey: 0x7C, keyDown: true)
    key?.flags = .maskControl
        
    key?.post(tap: .cghidEventTap)
}

but it works just like simple arrow click. How can I make it work right?


Solution

  • An event tap shows that the arrow keys have the .maskSecondaryFn flag set (and fn-arrows don't). This code emulates the events of a manually pressed Control-Right Arrow:

    func rightScreen() {
        guard let controlDown = CGEvent(keyboardEventSource: nil, virtualKey: 0x3B, keyDown: true) else {
            return
        }
        controlDown.flags = .maskControl
        
        guard let keyDown = CGEvent(keyboardEventSource: nil, virtualKey: 0x7C, keyDown: true) else {
            return
        }
        keyDown.flags = [.maskControl, .maskSecondaryFn]
        
        guard let keyUp = CGEvent(keyboardEventSource: nil, virtualKey: 0x7C, keyDown: false) else {
            return
        }
        keyUp.flags = [.maskControl, .maskSecondaryFn]
    
        guard let controlUp = CGEvent(keyboardEventSource: nil, virtualKey: 0x3B, keyDown: false) else {
            return
        }
        
        controlDown.post(tap: .cghidEventTap)
        keyDown.post(tap: .cghidEventTap)
        keyUp.post(tap: .cghidEventTap)
        controlUp.post(tap: .cghidEventTap)
    }