Python 模拟媒体键

Python simulate media keys

如何使 Python (3.7) 操纵当前正在 Windows 上运行的任何媒体播放器?

我想获得类似于键盘上媒体键的功能,例如:

澄清一下:我不想 Python 虚拟地按下键盘上的实际媒体键。我想获得这些键的功能,这样即使键盘没有连接到 PC 也能工作。

最简单的解决方案是使用 win32api.keybd_event from pywin32

例如安装pywin32

pip install pywin32

然后尝试 play/pause - 应该可以在没有键盘的情况下工作:

import win32api
from win32con import VK_MEDIA_PLAY_PAUSE, KEYEVENTF_EXTENDEDKEY

win32api.keybd_event(VK_MEDIA_PLAY_PAUSE, 0, KEYEVENTF_EXTENDEDKEY, 0)

虚拟键代码:here and here

注意:
this link about keybd_event function, you can see message: "Note This function has been superseded. Use SendInput 而不是.
所以如果你want/need使用SendInput,你可能需要使用ctypes. I suggest you to check the example here。我也尝试过该代码并且它有效。如果您需要任何进一步的帮助,请告诉我。