Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Ctypes Keyboard Event

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:

  1. Why does this hold down the alt key?
  2. How do I stop this in my code?
  3. Why does this not work with the alt keycode or the left-menu keycode?

Thank you in advance to anyone who helps.

like image 376
Sank6 Avatar asked Apr 16 '26 23:04

Sank6


1 Answers

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
like image 61
cooljoe Avatar answered Apr 19 '26 11:04

cooljoe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!