在Python中使用win32api检测按键

2024-05-16 00:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用win32api用一个特定的按键来打破Python中的循环。怎么办?

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

修订版:

import win32api

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

我想通过按h键来中断循环。

编辑:

我试图做一个程序,反复报告鼠标位置,我需要一个机制退出说的程序。

见修订规范。


Tags: 代码import程序版本trueifcp按键
3条回答

这不是它在GUI编程中的工作方式。你不需要调用方法来检查按键。相反,当按键时,你会收到信息。假设您有一个接收输入的窗口,那么您需要响应窗口过程中到达的WM_KEYDOWN消息,或者Python win32api术语中的消息映射。


您的编辑显示您没有使用消息队列,这是相当不寻常的。您可以通过调用^{}来实现您的愿望。

检查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

win32api只是底层windows低级库的接口。 请参见^{} 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

相关问题 更多 >