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

Viewed 2454

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

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.

3 Answers

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

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