Detect mouse position with conditions - python

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

Related

Python pyautogui/pynput click function

I tried making a simple autoclicker but it is not working for me.My cursor is moving slowly as f***.
You guys have an idea how to fix this?
Problem: line 11, pyautogui.click(button='left') is not clicking.
from pynput.mouse import Listener, Button, Controller
import pyautogui
# This function will be called when any key of mouse is pressed
def on_click(*args):
# see what argument is passed.
print(args)
if args[-1]:
# Do something when the mouse key is pressed.
print('The "{}" mouse key has held down'.format(args[-2].name))
pyautogui.click(button='left') # <--- lagging mouse
elif not args[-1]:
# Do something when the mouse key is released.
print('The "{}" mouse key is released'.format(args[-2].name))
# Open Listener for mouse key presses
with Listener(on_click=on_click) as listener:
# Listen to the mouse key presses
listener.join()
Supposing this is on a while or for loop, you can make it faster by changing the pyautogui.pause variable. Write this on top of your code:
pyautogui.PAUSE = .001
It specifies the delay between each pyautogui function call.
On my Windows 10 Computer running the topic poster code from question led to Python window that doesn't close for an hour and I can't close it with Task Manager.
So be careful with executing this code.

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 do I extract X,Y screen coordinates from listener thread pynput?

I'm unable to access values for screen X,Y coordinates when using mouse.Listener (Pynput)
I am trying to build a screen capture tool using pynput, Pillow (ImageGrab) and OpenCV (cv2) and need to store X,Y screen coordinates in separate variables.
I've tired returning x,y variables from within the on_click() function and tried assigning the mouse.Listener (threading function) to a variable with no luck (just returns )
The function works correctly and accurately displays the X,Y coordinates on pressing and releasing the mouse.
Is there a way to store the X,Y coordinates obtained on mouse pressing and release ?
Mac OSX 10.13.6, Python 3.7.3.
from pynput import mouse
def on_click(x, y, button, pressed):
if pressed:
print(f"start_pos = ({x},{y})")
elif not pressed:
print(f"end_pos = ({x},{y})")
return False
listener = mouse.Listener(on_click=on_click)
listener.start()
I cannot store the values from the output thread object.
If you import Controller from pynput and use it as such;
mouse = Controller()
mouse.position
Hope it helps!

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

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

Categories

Resources