After searching for several hours i´m wondering if its possible to simulate a keydown press on the keyboard. For example I want my program to hold the x key down for five seconds so when I run it in notepad it would look like to see something like this: xxxxxxxxxxxxx
. I tried around with different pieces of code on the internet, the best thing I could find so far is this:
import ctypes
import time
user32 = ctypes.windll.user32
inputhex = raw_input("Please enter your desired key's code (HEX): ")
keycode = int(inputhex, 16)
time.sleep(1)
#VOID keybd_event(BYTE bVk, BYTE bScan, DWORD dwFlags, PTR dwExtraInfo);
user32.keybd_event(keycode,0,2,0) #is the code for KEYDOWN
time.sleep(5)
#user32.keybd_event(keycode,0,0,0) #is the code for KEYDUP[/code]
The Sendkey module doesn't solve my problem either becuase it only allows you to send a single keypress and not a hold key down event. I know about autoit, used it in the past, but I just really want to know if this is possible with python and how. P.S. i'm using python for windows
I know that this question is really old, but I found a nice library:
PyUserInput
. I am not sure how to download it in windows(I haven't downloaded libraries for windows since long time ago). In linux is easy just download pip(if you haven't):sudo apt-get install pip
and thensudo pip install pyuserinput
. And then the code is realy simple:This code should get you started.
ctypes
is used heavily. At the bottom, you will see example code.I've modified the Noctis answer to work with Unicode characters.
"Simple unicode keyboard automation for windows" https://gist.github.com/ubershmekel/4b414a66037feaea595b5f4e78220aad
The above link has a gist, this is the code from that gist today:
If you're using Python for Windows then there's a very good chance that you have the
win32api
module, which handles hooking into the API for you...Does that help? (p.s. you should install IPython if at all possible, it's massively helpful for experimenting)