Reputation: 497
I have some Python 2.7 code as follows:
import ctypes
ctypes.windll.user32.keybd_event(0xA5, 0, 0, 0) # Right Menu Key
ctypes.windll.user32.keybd_event(0x73, 0, 0, 0) # F4
ctypes.windll.user32.keybd_event(0x0D, 0, 0, 0) #Enter Key
Whenever I run the code my computer bugs out, even after I close Python. It seems that the alt key is always pressed. This stops if I manually press the alt key.
Another thing is that this code is meant to close the shell. It only works with the right menu keycode and not the alt keycode nor the left menu keycode. (I know there are other ways to close the shell, but this closes anything.)
Here is what I want to know:
Thank you in advance to anyone who helps.
Upvotes: 3
Views: 8588
Reputation: 17
I don't know if you are still looking for an answer, but I believe the issue lies in the fact that you aren't simulating the key up command. Adding the three lines of code below should be able to simulate what you are looking for.
For the below code, I am assuming that you want it sequentially(i.e. press the right menu key, press the F4 key, then press enter). If, however, you want to hold it down, as in the case of Shift + 'a', you would call both key down events then both key up events.
import ctypes
ctypes.windll.user32.keybd_event(0xA5, 0, 0, 0) # Right Menu Key Down
ctypes.windll.user32.keybd_event(0xA5, 0, 0x0002, 0) # Right Menu Key Up
ctypes.windll.user32.keybd_event(0x73, 0, 0, 0) # F4 Down
ctypes.windll.user32.keybd_event(0x73, 0, 0x0002, 0) # F4 Up
ctypes.windll.user32.keybd_event(0x0D, 0, 0, 0) #Enter Key Down
ctypes.windll.user32.keybd_event(0x0D, 0, 0x0002, 0) #Enter Key Up
Upvotes: 2
Reputation: 10010
You can use pywinauto to emulate user input. Your problem is already solved inside it. Submodule pywinauto.keyboard can be used so:
from pywinauto.keyboard import SendKeys
SendKeys('%{F4}{PAUSE 0.2}{ENTER}') # press Alt+F4, pause, press Enter
Just run pip install pywinauto
in a command line before.
Upvotes: 0