[英]How to click mouse button rapidly when key is held down
how do I trigger the mouse being clicked rapidly when a key is held down (shift key in this instance).当按下某个键(在本例中为 shift 键)时,如何触发快速单击鼠标。 My code is currently
我的代码目前是
import win32api
import win32con
import time
from pynput.mouse import Button, Controller
mouse = Controller()
while True:
keystate = win32api.GetAsyncKeyState(0x10)
if keystate < 0:
mouse.click(Button.left, 2)
else:
pass
The issue I'm having is everytime I actually press the shift key the program crashes.我遇到的问题是每次我实际按下 shift 键程序崩溃。 When printing out the keystate it shows 0 until shift is pressed in which it shows -32767 and then it stops printing and I have to kill the process.
当打印出键状态时,它显示 0 直到按下 shift,其中它显示 -32767,然后它停止打印,我必须终止该过程。 How do I stop this from happening.
我该如何阻止这种情况发生。
I don't use Windows but Linux so I can't check it but program runs very fast and it runs loop a lot of times in one second, and it checks shift
a lot of times in one second, and it click button a lot of times in one second, and this may make problem.我不使用 Windows 但 Linux 所以我无法检查它但是程序运行非常快并且它在一秒钟内循环运行了很多次,并且它在一秒钟内检查了很多次
shift
,并且它点击了很多按钮一秒钟内多次,这可能会产生问题。
You can use second variable to remeber previous_keystate
and click button only when previous_keystate == 0
您可以使用第二个变量来记住
previous_keystate
并仅在previous_keystate == 0
时单击按钮
import win32api
import win32con
import time
from pynput.mouse import Button, Controller, Listener
mouse = Controller()
previous_keystate = 0
while True:
keystate = win32api.GetAsyncKeyState(0x10)
if previous_keystate == 0 and keystate < 0:
mouse.click(Button.left, 2)
previous_keystate = keystate
BTW: as I rember in documentation you can find information that click(Button.left, 2)
may not work on some systems.顺便说一句:正如我在文档中所记得的那样,您可以找到有关
click(Button.left, 2)
在某些系统上可能不起作用的信息。
I would use pynput.keyboard.Listener
to get pressed key - it execute function only once when key is pressed (and not repeate function when key is keep pressed).我会使用
pynput.keyboard.Listener
来获取按下的键 - 它仅在按下键时执行一次 function(并且在按住键时不重复 function)。 And it works also on Linux.它也适用于 Linux。
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Listener
# --- functions ---
def on_press(key):
#print(key)
if key == Key.shift:
mouse.click(Button.left, 2)
# to stop on ESC
if key == Key.esc:
return False
# --- main ---
mouse = Controller()
with Listener(on_press=on_press) as listener:
# ... some code ...
listener.join()
or要么
# --- main ---
mouse = Controller()
listener = Listener(on_press=on_press)
listener.start()
# ... some code ...
listener.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.