swiftmacoskeypressmedia-keys

Simulate Media-Key press in MacOS


I would like to simulate media keypresses from within an app on Mac OS. I am using Swift in Xcode 10 on Mojave 10.14.4

Using answers such as Simulate keypress using Swift I can simulate a variety of keys, but not the media transport keys (play/pause, VolumeUp etc.).

import Carbon.HIToolbox.Events

    @IBAction func buttonPressed(_ sender: AnyObject) {

        //let keyCode = CGKeyCode(kVK_F11)
        let keyCode = CGKeyCode(kVK_VolumeUp)
        let keySource = CGEventSource(stateID: .hidSystemState)

        let keyDownEvent = CGEvent(keyboardEventSource: keySource,
                                   virtualKey: keyCode,
                                   keyDown: true)
        //keyDownEvent?.flags = .maskCommand
        //keyDownEvent?.flags = .maskControl
        //keyDownEvent?.flags = .maskAlternate
        //keyDownEvent?.flags = .maskSecondaryFn
        //keyDownEvent?.flags = .maskShift
        //keyDownEvent?.flags = .maskNumericPad
        //keyDownEvent?.flags = .maskHelp

        let keyUpEvent = CGEvent(keyboardEventSource: keySource,
                                 virtualKey: keyCode,
                                 keyDown: false)

        keyDownEvent?.post(tap: .cghidEventTap)
        keyUpEvent?.post(tap: .cghidEventTap)
    }

If I create an event for the key kVK_F11 (which is the VolumeUp key by default) it performs its non-media function, i.e. causing all windows to flee to the edges of the screen. I did try the different flags modifiers on the keyDown event to no avail.

Is there a way to generate a keypress event for Play/Pause, VolumeUp/Down etc. programmatically?


Solution

  • The suggested duplicate question emulate media key press on Mac identified by https://stackoverflow.com/users/4244136/willeke in comments above includes a python solution to my question. I translated it to Swift and posted the working code there. Thanks!