Search code examples
pythonkeyboardmousepyautoguipynput

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


Solution

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