在 Python 中使用 win32api 检测按键
我正在尝试使用 win32api 通过特定按键来打破 Python 中的循环。人们会怎样做呢?
以下代码中 win32api.KeyPress('H') 的实际版本是什么?
修订:
import win32api
while True :
cp = win32api.GetCursorPos()
print cp
if win32api.KeyPress('H') == True :
break
我希望能够通过按h键来中断循环。
编辑:
我正在尝试制作一个重复报告鼠标位置的程序,我需要一种退出所述程序的机制。
请参阅修改后的代码。
I'm trying to break a loop in Python with a specific key press using win32api. How would one go about this?
What is the actual version of win32api.KeyPress('H'), in the following code?
Revised:
import win32api
while True :
cp = win32api.GetCursorPos()
print cp
if win32api.KeyPress('H') == True :
break
I want to be able to break a loop by pressing the h key.
Edit:
I'm attempting to make a program that repeatedly reports mouse positions and I need a mechanism to exit said program.
See revised code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
win32api
只是底层 Windows 低级库的接口。请参阅
GetAsyncKeyState
函数:请注意,返回值是位编码的(不是
boolean
)。要获取
vKey
值,应用程序可以使用win32con
模块中的虚拟键代码常量。例如,测试“CAPS LOCK”键:
简单字母的虚拟键常量是 ASCII 代码,
这样测试“H”键(按键被按下)的状态将如下所示:
win32api
is just an interface to the underlying windows low-level library.See the
GetAsyncKeyState
Function:Note that the return value is bit-encoded (not a
boolean
).To get at
vKey
values, an application can use the virtual-key code constants in thewin32con
module.For example, testing the "CAPS LOCK" key:
The virtual-key constant for simple letters are ASCII codes,
so that testing the state of the "H" key (key was pressed) will look like:
这不是 GUI 编程的工作方式。您不会调用方法来检查按键情况。相反,当按下按键时您会收到发送的消息。假设您有一个正在接收输入的窗口,那么您需要响应到达窗口过程的
WM_KEYDOWN
消息,或者 Python win32api 术语中的消息映射。您的编辑表明您没有使用消息队列,这是相当不寻常的。您可以通过调用
GetAsyncKeyState()
。This isn't how it works in GUI programming. You don't call a method to check for a key press. Instead you get sent messages when keys are pressed. Assuming that you have a window that is receiving input then you need to respond to the
WM_KEYDOWN
message arriving in your window procedure, or message map in Python win32api terms.Your edit shows that you are not using the message queue which is rather unusual. You may be able to achieve what you wish by calling
GetAsyncKeyState()
.检查 github 上的 python tiler,即使您只是想查找要发送的关键代码,它也非常有用。此外,如果您在后台运行代码并希望从窗口外部中断循环,这也会很有用。
git 项目:
https://github.com/Tzbob/python-windows-tiler
带有 Windows 键的代码:
https://code.google .com/p/python-windows-tiler/source/browse/pwt/hotkey.py?r=df41af2a42b6304047a5f6f1f2903b601b22eb39
Check the python tiler on github, very useful even if you are trying to just find key codes to send. Also this will be useful if you are running your code in the background and want to break the loop from outside the window.
git project:
https://github.com/Tzbob/python-windows-tiler
code with windows keys:
https://code.google.com/p/python-windows-tiler/source/browse/pwt/hotkey.py?r=df41af2a42b6304047a5f6f1f2903b601b22eb39