Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

winapi - Detecting Key Presses using win32api in Python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...