问题
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.
回答1:
You can use win32api.PostMessage
to send WM_KEYDOWN
and WM_KEYUP
messages. See MSDN for documentation of the parameters. The constants are defined in win32con
module.
来源:https://stackoverflow.com/questions/9271761/how-to-emulate-press-and-hold-with-pywin32