How do you hold down left click with python? - python

I know that you can hold down certain keys with pyautogui, but is there a way to hold down the left click key with keyDown and keyUp (or with another module)? Thanks in advance if you help.

From the documentation you can use mouseDown():
>>> pyautogui.mouseDown(); pyautogui.mouseUp() # does the same thing as a left-button mouse click
>>> pyautogui.mouseDown(button='right') # press the right button down
>>> pyautogui.mouseUp(button='right', x=100, y=200) # move the mouse to 100, 200, then release the right button up.

pyautogui.click() # Left click
pyautogui.click(button='right') # Right click
This is the docs for the mouse control functions of pyautogui.

Related

Make loop run only when holding right click

I'm trying to make a program that randomly moves the mouse only when the right mouse button is held to prank a friend.
I found some code online to detect right-clicks with Win32 API. When I added my own while loop, it didn't stop after it started. I tried adding an if statement with break but nothing changed.
import win32api
import pyautogui
import random
state = win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128
while True:
pressed = win32api.GetKeyState(0x02)
if pressed != state: # Button state changed
state = pressed
print(pressed)
if pressed < 0:
print('Right Button Pressed')
while pressed < 0: # If the right mouse button is pressed, move the mouse randomly.
pyautogui.moveRel(random.randint(-10, 10), random.randint(-10, 10))
if (pressed > 0):
break
else:
print('Right Button Released')
You can try replacing your main while loop with this one that uses the assignment (walrus) operator := to continuously check the button state
has_right_clicked = False # flag if the button has been pressed yet
while state := win32api.GetKeyState(0x02) # Right button down = 1. Button up = -128:
if state == 1: # If the right mouse button is pressed, move the mouse randomly.
has_right_clicked = True # user has right-clicked, set the flag
pyautogui.moveRel(random.randint(-10, 10), random.randint(-10, 10))
if has_right_clicked: # this will be ignored until the flag is set
break # if the user lets go of the button
The loop will start automatically because both 1 and 128 evaluate to True, which is why we need the extra has_right_clicked flag to break the loop! The caveat here, however, is that this loop will only run once. You should probably wrap this in a function that's bound to right-click so it can be called whenever the user right-clicks the mouse.
Waiting for input with GetKeyState is never the correct solution for anything.
To capture global mouse events you should probably use a low-level mouse hook in this case. I don't know if it is possible in Python but I assume there is a way...

Detect mouse position with conditions

I am trying to obtain the following functionality:
When I run my script I need to record the x,y coordinates of the first time I press and release the mouse. I need this to work both on Linux and Windows.
I have been able to read the position of the mouse with
pyautogui.position()
How can I trigger this position() function by a mouse press/release? I would like to extend this to e.g. trigger with a mouse event only if the Alt key is pressed down.
Can someone point me in the right direction, I am a bit lost, and I cant find this in pyautogui's documentation.
Check key press using keyboard :
import keyboard
import pyautogui
while True:
if keyboard.is_pressed('alt'):
print(pyautogui.position())
You can get the position only if the Alt key is pressed down and mouse left key is pressed by:
import pyautogui
import keyboard
import mouse
if keyboard.is_pressed('alt') and mouse.is_pressed(button='left'):
print(pyautogui.position())

Python check if Left Mouse Button is being held?

I'm pretty new to Python and I'd like to make a kind of an Autoclicker, which keeps clicking every 0.1 seconds when my left mouse button is held down.
My Problem is, that when I run my script, my mouse instantly starts clicking. What should I do?:
import win32api
import time
from pynput.mouse import Button, Controller
mouse = Controller()
while True:
if win32api.GetAsyncKeyState(0x01):
mouse.click(Button.left, 1)
time.sleep(0.1)
else:
pass
Thanks
My Problem is, that when I run my script, my mouse instantly starts clicking. What should I do?
If the function succeeds, the return value specifies whether the key
was pressed since the last call to GetAsyncKeyState, and whether the
key is currently up or down. If the most significant bit is set, the
key is down, and if the least significant bit is set, the key was
pressed after the previous call to GetAsyncKeyState.
You should use win32api.GetAsyncKeyState(0x01)&0x8000 instead.
Now, the only thing it does is click once, which makes my click a double click.
Because GetAsyncKeyState detects the key state of the left mouse button. When you press the left mouse button, the click function is called, click will realize the two actions of the left mouse button press and release. Then in the place of the while loop, GetAsyncKeyState will detect the release action, which is why it stops after double-clicking.
I suggest you set the left mouse button to start and the right mouse button to stop.
Code Sample:
import win32api
import time
from pynput.mouse import Button, Controller
mouse = Controller()
while True:
if (win32api.GetAsyncKeyState(0x01)&0x8000 > 0):
flag = True
while flag == True:
mouse.click(Button.left, 1)
time.sleep(0.1)
if (win32api.GetAsyncKeyState(0x02)&0x8000 > 0):
flag = False
else:
pass
Check if win32api.GetAsyncKeyState(0x01) < 0 in the if condition.
I made it work with mouse5!
import win32api
import win32con
import time
from pynput.mouse import Button, Controller
mouse = Controller()
def ac():
if keystate < 0:
mouse.click(Button.left, 1)
time.sleep(0.1)
else:
pass
while True:
keystate = win32api.GetAsyncKeyState(0x06)
ac()

How to know if the left mouse click is pressed

I am using PyAutoGUI library. How can I know if the left mouse button is pressed?
This is what I want to do:
if(leftmousebuttonpressed):
print("left")
else:
print("nothing")
(I'm the author of PyAutoGUI.) I can confirm that currently PyAutoGUI can't read/record clicks or keystrokes. These features are on the roadmap, but there aren't any resources or timelines dedicated to them currently.
How to know if left mouse click is pressed?
A simple version of the code inspired from the original documentation:
from pynput import mouse
def on_click(x, y, button, pressed):
if button == mouse.Button.left:
print('{} at {}'.format('Pressed Left Click' if pressed else 'Released Left Click', (x, y)))
return False # Returning False if you need to stop the program when Left clicked.
else:
print('{} at {}'.format('Pressed Right Click' if pressed else 'Released Right Click', (x, y)))
listener = mouse.Listener(on_click=on_click)
listener.start()
listener.join()
Like Sir Al Sweigart mentioned in the comment above, I looked for pynput module which works perfect. See documentation and PyPi instructions at:
https://pynput.readthedocs.io/
https://pypi.org/project/pynput/
Install the library using pip: pip install pynput
Monitoring other events (e.g. Mouse move, click, scroll)
See the code under Monitoring the mouse heading from original documentation.
https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse
I don't think you can use PyAutoGui to listen for mouseclick.
Instead try Pyhook (from their source page):
import pythoncom, pyHook
def OnMouseEvent(event):
# called when mouse events are received
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Position:',event.Position
print 'Wheel:',event.Wheel
print 'Injected:',event.Injected
print '---'
# return True to pass the event to other handlers
return True
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.MouseAll = OnMouseEvent
# set the hook
hm.HookMouse()
# wait forever
pythoncom.PumpMessages()
I believe you can you do this:
import pyHook, pythoncom
def left_down():
print("left down")
def right_down():
print("right down")
hm = pyHook.HookManager()
hm.SubscribeMouseLeftDown(left_down)
hm.SubscribeMouseRightDown(right_down)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
They also do keyboards events, just go look their api up.
Edit:
Here's their mini tutorial: https://sourceforge.net/p/pyhook/wiki/PyHook_Tutorial/
Also PyHook is only for windows (thanks to John Doe for pointing it out)
you can use win32api which is a built-in library as in the following example:
import win32api
if win32api.GetKeyState(0x01)<0: #if mouse left button is pressed
#do something
else: #if mouse left button is not pressed
#do something
as for why that code functions like that here's the explanation:
you do "<0" because the GetKeyState function returns either a negative number or 1 or 0, 1 or 0 are for when the button is released and it changes each time u let go and the negative number is for when the button is pressed, as an example if the mouse button is now returning a 0 using the GetKeyState function and you press it it will return a negative number until u let go and then it will return 1, and if it was a 1 and u press the button it will return a negative number while your holding it down and then once u let go it will go back to being 0 (you can print(GetKeyState(0x01) and see for yourself for a better understanding), as for "0x01" thats the virtual key code for the left mouse button and you can find all the virtual keycodes of each and every button on the mouse and the keyboard using this site provided by microsoft themselves https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

tkinter: How to automatically scroll using middle mouse button?

right now I have an implementation where I'm using my middle mouse button for two operations:
Zooming (in and out) by rolling the wheel and
Scrolling the wheel button to scroll(pan) left, right, top and bottom. But in this feature, I have press and hold the scroll button continuously, only then can I scroll.
What I wish to do is:
Press and release the middle mouse button to enter scrolling mode.
Then, simply, move the mouse left and right and, top and bottom, to scroll in the respective directions.
Once done, press and release the middle mouse button to come out of this mode.
It is just like how it is implemented in MS Word or Chrome browser.
Help!
Here's a quick simple thing of what I believe you're after.
import tkinter as tk
root = tk.Tk()
pressed = False
def onClick(event):
global pressed
pressed = not pressed # toggle pressed when clicked
print('Pressed')
def onMove(event):
if pressed:
print(event.x, event.y)
root.bind('<Button-2>', onClick)
root.bind('<Motion>', onMove)
root.mainloop()

Categories

Resources