1

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.

dave
  • 1,607
  • 3
  • 16
  • 20
  • 2
    I think this [post](http://stackoverflow.com/a/2004267/673590) might be what you are after. – tharen Feb 14 '12 at 08:02

1 Answers1

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.

Janne Karila
  • 24,266
  • 6
  • 53
  • 94
  • 2
    Can you provide an example? The documentation is really difficult for me to sift through. See edit. – dave Feb 14 '12 at 16:22