我正在嘗試制作一個僅在按住滑鼠右鍵以惡作劇朋友時隨機移動滑鼠的程式。
我在網上找到了一些代碼來檢測 Win32 API 的右鍵單擊。當我添加自己的while回圈時,它開始后并沒有停止。我嘗試添加一個if陳述句,break但沒有任何改變。
import win32api
import pyautogui
import random
state = win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128
while True:
pressed = win32api.GetKeyState(0x02)
if pressed != state: # Button state changed
state = pressed
print(pressed)
if pressed < 0:
print('Right Button Pressed')
while pressed < 0: # If the right mouse button is pressed, move the mouse randomly.
pyautogui.moveRel(random.randint(-10, 10), random.randint(-10, 10))
if (pressed > 0):
break
else:
print('Right Button Released')
uj5u.com熱心網友回復:
您可以嘗試用while這個使用賦值(海象)運算子:=來不斷檢查按鈕狀態的回圈替換主回圈
has_right_clicked = False # flag if the button has been pressed yet
while state := win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128:
if state == 1: # If the right mouse button is pressed, move the mouse randomly.
has_right_clicked = True # user has right-clicked, set the flag
pyautogui.moveRel(random.randint(-10, 10), random.randint(-10, 10))
if has_right_clicked: # this will be ignored until the flag is set
break # if the user lets go of the button
回圈將自動啟動,因為1和都128計算為True,這就是為什么我們需要額外的has_right_clicked標志來打破回圈!然而,這里需要注意的是,這個回圈只會運行一次。您可能應該將其包裝在系結到右鍵單擊的函式中,以便用戶右鍵單擊滑鼠時可以呼叫它。
uj5u.com熱心網友回復:
等待輸入GetKeyState永遠不是任何事情的正確解決方案。
在這種情況下,要捕獲全域滑鼠事件,您可能應該使用低級滑鼠掛鉤。我不知道在 Python 中是否可行,但我認為有一種方法......
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528422.html
