-->

How to simulate a mouse click while holding the SH

2019-06-15 18:56发布

问题:

Hello I'm trying to simulate a mouse click while holding the SHIFT key. I have been trying to do this with the pynput module.

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

time.sleep(5)

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"). 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

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.

回答1:

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. 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



回答2:

Thanks to finefoot I managed to find a solution.

It turns out that the target (program I want to perform the Shift + Left-Click on) was the problem.

The solution here was to focus on the target first by going to the target. This is done by performing a simple Left-Click on the target so the target is in focus. Then the script will work!



回答3:

Well a workaround i suggest is creating an event listener like this :


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