如何在Windows中按住SHIFT键模拟鼠标点击?

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

您好,我正在尝试在按住 SHIFT 键的同时模拟鼠标单击。我一直在尝试使用 pynput 模块来做到这一点。

到目前为止,这是我的代码:

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)

我知道按住 shift 键的代码有效(如果我尝试按 "a" 代码中的按钮我看到一个 "A")。我也知道鼠标点击是有效的。但是,放在一起是不行的。


我还尝试了来自 Whosebug post 的另一个代码:Pyautogui - Need to hold shift and click

我从中尝试了以下代码:

import pyautogui

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

这工作了一分钟然后就停止工作了!很奇怪。 10 次中有 9 次失败。

嗯,我建议的解决方法是创建一个这样的事件侦听器:

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()

该脚本按预期工作,但您尝试应用 Shift + target 似乎Left-Click 不接受此类输入,而 Windows GUI 上的 window 未处于焦点。这就是为什么当你在 Shift + Left-Click[= 之前​​包含 Left-Click 时它起作用的原因22=],因为第一次点击使目标 window(无论 program/app 是什么)成为焦点,然后已经工作但被忽略的 Shift + Left-Click 也被 target

接受

您应该给它添加一个计时器,这很可能会起作用。

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')