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

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

问题描述

我正在尝试使用 win32api 通过特定的按键来中断 Python 中的循环.怎么办呢?

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

修订:

导入win32api而真:cp = win32api.GetCursorPos()打印cp如果 win32api.KeyPress('H') == True :休息

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

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

查看修改后的代码.

解决方案

win32api 只是 Windows 底层库的一个接口.请参阅 GetAsyncKeyState 函数:

<块引用>

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

语法

SHORT WINAPI GetAsyncKeyState(__in int vKey);

<块引用>

返回值

类型:SHORT

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

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

例如,测试CAPS LOCK"键:

<预><代码>>>>导入 win32api>>>导入 win32con>>>win32con.VK_CAPITAL20>>>win32api.GetAsyncKeyState(win32con.VK_CAPITAL)0>>>win32api.GetAsyncKeyState(win32con.VK_CAPITAL)1

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

<预><代码>>>>win32api.GetAsyncKeyState(ord('H'))1

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.

解决方案

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

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.

Syntax

SHORT WINAPI GetAsyncKeyState(
__in  int vKey
);

Return Value

Type: SHORT

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.

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.

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

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天全站免登陆