如何使用 pywin32 模拟按住
我正在尝试编写一个 python 脚本来发送按住键信号。现在我所能做的就是以下内容:
import win32com.client
shell = win32com.client.Dispatch("Wscript.Shell")
shell.SendKeys("z")
但是,这仅发送瞬时按键事件。我想做的是按一下键然后向上按一下键,大致如下:
shell.SendKeys("z{down}")
time.sleep(.25)
shell.SendKeys("z{up}")
但我找不到任何有记录的方法来实现此目的。
编辑:我也尝试了类似的方法:
import time
import win32com.client
import win32api
import win32gui
import win32con
time.sleep(2)
shell = win32com.client.Dispatch("Wscript.Shell")
win32api.SendMessage(win32con.HWND_TOP, win32con.WM_CHAR, 90, 0)
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_KEYDOWN, 90, 1)
time.sleep(.25)
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_KEYUP, 90, 1)
整个 HWND 事情对我来说确实是一个谜 - 从文档中我无法弄清楚如何获取正确的窗口。另外,WM_CHAR 似乎可以工作,但 WM_KEYDOWN/KEYUP 并没有真正执行任何操作。
I am trying to write a python script to send a press and hold key signal. Right now all I have managed to do is the following:
import win32com.client
shell = win32com.client.Dispatch("Wscript.Shell")
shell.SendKeys("z")
However, this only sends an instantaneous key pressed event. What I would like to do is a key down and key up, something along the lines of:
shell.SendKeys("z{down}")
time.sleep(.25)
shell.SendKeys("z{up}")
But I cannot find any documented way to achieve this.
EDIT: I also tried something along the lines of this:
import time
import win32com.client
import win32api
import win32gui
import win32con
time.sleep(2)
shell = win32com.client.Dispatch("Wscript.Shell")
win32api.SendMessage(win32con.HWND_TOP, win32con.WM_CHAR, 90, 0)
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_KEYDOWN, 90, 1)
time.sleep(.25)
win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_KEYUP, 90, 1)
The whole HWND thing is really a mystery to me - from the documentation I can't figure out how the hell to grab the correct window. Also, WM_CHAR seems to work, but WM_KEYDOWN/KEYUP hasn't really done anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
win32api.PostMessage
发送WM_KEYDOWN
和WM_KEYUP
消息。有关参数的文档,请参阅 MSDN。这些常量在win32con
模块中定义。You can use
win32api.PostMessage
to sendWM_KEYDOWN
andWM_KEYUP
messages. See MSDN for documentation of the parameters. The constants are defined inwin32con
module.您还可以按住鼠标按钮,对于左键,请参阅以下示例(即使与键盘无关,有人可能会发现它很有用..):
You can also press and hold mouse button, for left button see following example (someone may find it useful even though it is not about keyboard..):