title: Simulate Media-Key press in MacOS
body: <p>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</p>
  
  <p>Using answers such as <a href="https://stackoverflow.com/questions/27484330/simulate-keypress-using-swift">Simulate keypress using Swift</a> I can simulate a variety of keys, but not the media transport keys (play/pause, VolumeUp etc.).</p>
  
  <pre><code>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)
      }
  </code></pre>
  
  <p>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.</p>
  
  <p>Is there a way to generate a keypress event for Play/Pause, VolumeUp/Down etc. programmatically?</p>