Skip to main content
 首页 » 编程设计

python之在 Python 中使用 win32api 检测按键

2025年05月04日9落叶

我正在尝试使用 win32api 通过特定的按键来打破 Python 中的循环。如何解决这个问题?

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

修订:

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

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

编辑:

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

请参阅修改后的代码。

请您参考如下方法:

win32api 只是底层 windows 低级库的接口(interface)。 查看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.

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

例如,测试“CAPS LOCK”键:

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

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

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