简体   繁体   English

如何在 Windows 中按住 SHIFT 键的同时模拟鼠标单击?

[英]How to simulate a mouse click while holding the SHIFT key in Windows?

Hello I'm trying to simulate a mouse click while holding the SHIFT key.您好,我正在尝试在按住SHIFT键的同时模拟鼠标单击。 I have been trying to do this with the pynput module.我一直在尝试使用pynput模块来做到这一点。

This is my code so far:到目前为止,这是我的代码:

from pynput.keyboard import Key
from pynput.keyboard import Controller as Cont
from pynput.mouse import Button, Controller
import time

mouse = Controller()
keyboard = Cont()

with keyboard.pressed(Key.shift):
    mouse.position = (1892, 838)
    mouse.click(Button.left)

I know the code for holding the shift key is working (If I try to press the "a" button in the code I see an "A").我知道按住 shift 键的代码有效(如果我尝试按代码中的“a”按钮,我会看到“A”)。 Also I know the mouse click is working.我也知道鼠标点击有效。 However, together it does not work.但是,放在一起是行不通的。


Also I tried another code from a StackOverflow post: Pyautogui - Need to hold shift and click我还尝试了 StackOverflow 帖子中的另一个代码: Pyautogui - Need to hold shift and click

I tried the following code from it:我尝试了以下代码:

import pyautogui

pyautogui.keyDown('shift')
pyautogui.click()
pyautogui.keyUp('shift')

This worked for a minute then it stopped working!这工作了一分钟然后它停止工作! Very strange.很奇怪。 It fails like 9 out of 10 times.它失败了 10 次中有 9 次。

The script works as intended, but it seems the target on which you are trying to apply Shift + Left-Click is not accepting such inputs while its window on Windows GUI is not in focus.该脚本按预期工作,但它似乎对你尝试应用Shift +左键单击不接受这样的投入,同时其在Windows GUI窗口不是焦点目标 That is why it works when you include a Left-Click before the Shift + Left-Click , because that first click puts the target window (whatever program/app it is) in focus, then the already working but ignored Shift + Left-Click is also accepted by the target这就是为什么它的工作原理,当您在焦点左键点击Shift +左键单击之前,因为第一次点击放目标窗口(任何程序/应用它),那么已经工作,但忽略了Shift键+鼠标左键点击也被目标接受

You should add a timer to it most likely will work.您应该为其添加一个计时器,这很可能会起作用。

import pyautogui
import time

#cordinates
cordinates = 100,100
pyautogui.keyDown('shift')
time.sleep(0.15)
pyautogui.click(cordinates)
time.sleep(0.15)
pyautogui.keyUp('shift')

Well a workaround i suggest is creating an event listener like this :好吧,我建议的解决方法是创建一个这样的事件侦听器:

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

enter code hereCollect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM