在Python中使用win32api检测按键 [英] Detecting Key Presses using win32api in Python

查看:852
本文介绍了在Python中使用win32api检测按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用win32api通过特定的按键来打破Python中的循环.怎么会这样呢?

I'm trying to break a loop in Python with a specific key press using win32api. How would one go about this?

在以下代码中, win32api.KeyPress('H')的实际版本是什么?

What is the actual version of win32api.KeyPress('H'), in the following code?

修订版:

import win32api

while True :
    cp = win32api.GetCursorPos()
    print cp
    if win32api.KeyPress('H') == True :
        break

我希望能够通过按 h 键来中断循环.

I want to be able to break a loop by pressing the h key.

我正在尝试制作一个重复报告鼠标位置的程序,并且我需要一种机制来退出所述程序.

I'm attempting to make a program that repeatedly reports mouse positions and I need a mechanism to exit said program.

请参阅修订后的代码.

See revised code.

推荐答案

win32api只是基础Windows低层库的接口. 请参见 GetAsyncKeyState函数:

win32api is just an interface to the underlying windows low-level library. See the GetAsyncKeyState Function:

确定在调用函数时按键是向上还是向下,以及在上次调用GetAsyncKeyState之后是否按下了该键.

Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

语法

SHORT WINAPI GetAsyncKeyState(
__in  int vKey
);

返回值

类型:SHORT

如果函数成功,则返回值指定自上次调用GetAsyncKeyState以来是否按下了该键,以及该键当前处于向上还是向下.如果设置了最高有效位,则该键处于按下状态;如果设置了最低有效位,则在上一次调用GetAsyncKeyState之后按下了该键.

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState.

请注意,返回值是位编码的(不是boolean). 为了获得vKey值,应用程序可以使用win32con模块中的虚拟键代码常量.

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 the win32con module.

例如,测试"CAPS LOCK"键:

For example, testing the "CAPS LOCK" key:

>>> import win32api
>>> import win32con
>>> win32con.VK_CAPITAL
20
>>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL)
0
>>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL)
1

简单字母的虚拟键常数是ASCII码, 这样测试"H"键(按下键)的状态将如下所示:

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:

>>> win32api.GetAsyncKeyState(ord('H'))
1

这篇关于在Python中使用win32api检测按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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