Python Ctypes 键盘事件 [英] Python Ctypes Keyboard Event

查看:48
本文介绍了Python Ctypes 键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些 Python 2.7 代码如下:

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

每当我运行代码时,我的计算机就会出错,即使在我关闭 Python 之后也是如此.似乎总是按下 alt 键.如果我手动按下 alt 键,这会停止.

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.

另一件事是此代码旨在关闭外壳.它仅适用于右侧菜单键码,不适用于 alt 键码或左侧菜单键码.(我知道还有其他方法可以关闭 shell,但这会关闭任何东西.)

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.)

这是我想知道的:

  1. 为什么这会按住 alt 键?
  2. 如何在我的代码中阻止它?
  3. 为什么这不适用于 alt 键码或左菜单键码?

提前感谢所有提供帮助的人.

Thank you in advance to anyone who helps.

推荐答案

我不知道你是否还在寻找答案,但我相信问题在于你没有模拟 key up 命令.添加下面的三行代码应该可以模拟您要查找的内容.

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.

对于下面的代码,我假设您需要按顺序(即按右键菜单键,按 F4 键,然后按 Enter).但是,如果您想按住它,例如在 Shift + 'a' 的情况下,您将调用两个键按下事件,然后调用两个键按下事件.

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

这篇关于Python Ctypes 键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆