Reputation: 1637
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.
Upvotes: 1
Views: 4986
Reputation: 1
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..):
import win32api, win32con
import time
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,500,500,0,0) #left mouse click and hold at 500px from left and 500px from upper edge of display
time.sleep(10) # wait 10 seconds
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,500,500,0,0) #left mouse button release
Upvotes: 0
Reputation: 25207
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.
Upvotes: 1