emulate media key press on Mac

前端 未结 3 1454
挽巷
挽巷 2020-12-16 05:41

Is there a way to emulate key presses of the media keys (volume up/down, play, pause, prev, next) on common Apple notebooks?

How?

3条回答
  •  既然无缘
    2020-12-16 06:15

    That took some time and many hacks (trying around with ctypes, the IOKit native interface, Quartz and/or Cocoa). This seems like an easy solution now:

    #!/usr/bin/python
    
    import Quartz
    
    # NSEvent.h
    NSSystemDefined = 14
    
    # hidsystem/ev_keymap.h
    NX_KEYTYPE_SOUND_UP = 0
    NX_KEYTYPE_SOUND_DOWN = 1
    NX_KEYTYPE_PLAY = 16
    NX_KEYTYPE_NEXT = 17
    NX_KEYTYPE_PREVIOUS = 18
    NX_KEYTYPE_FAST = 19
    NX_KEYTYPE_REWIND = 20
    
    def HIDPostAuxKey(key):
        def doKey(down):
            ev = Quartz.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
                NSSystemDefined, # type
                (0,0), # location
                0xa00 if down else 0xb00, # flags
                0, # timestamp
                0, # window
                0, # ctx
                8, # subtype
                (key << 16) | ((0xa if down else 0xb) << 8), # data1
                -1 # data2
                )
            cev = ev.CGEvent()
            Quartz.CGEventPost(0, cev)
        doKey(True)
        doKey(False)
    
    for _ in range(10):
        HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
    HIDPostAuxKey(NX_KEYTYPE_PLAY)
    

    (While I needed this in Python for now, my question was not really Python related and of course you can easily translate that to any other language, esp. ObjC.)

提交回复
热议问题