如何在 windows 中使用 pynput 按下媒体键?

How to press media keys using pynput in windows?

我需要按下播放媒体键,但找不到合适的键值

我试过

from pynput.keyboard import Key, Controller
keyboard= Controller()
keyboard.press(Key.MediaPlayPause)
keyboard.release(Key.MediaPlayPause)

但是不行 我没有收到任何错误

错误回溯

Traceback (most recent call last):
  File "2.py", line 63, in <module>
    keyboard.press(Key.MediaPlayPause)
  File "C:\Users\nebbu\AppData\Local\Programs\Python\Python37\lib\enum.py", line 349, in __getattr__
    raise AttributeError(name) from None
AttributeError: MediaPlayPause

更新:

Since pynput version 1.5.0 media keys are available for use. The available keys are described here: (https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key.media_next)


媒体控制在 pynput 上仍然不可用。 (https://github.com/moses-palmer/pynput/pull/171)

您可以使用虚拟键代码发出键输入事件:

from pynput.keyboard import Controller, KeyCode


def main():
    keyboard = Controller()

    print('Pausing/Resuming... ')

    keyboard.press(KeyCode.from_vk(0xB3))  # Play/Pause

if __name__ == "__main__":
    main()

In the sample we are using Play/Pause virtual key code (0xB3). You can check the full list of possible values here https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes