I am using pynput and so far i haven't figured it out i have tried arrow keys and teleporting the mouse relative to its position and to specified coordinates
from pynput.keyboard import Key, Controller as KeyboardController
from pynput.mouse import Button, Controller as MouseController
import time
keyboard = KeyboardController()
mouse = MouseController()
mouse.position = (-1756, 1079)
time.sleep(0.5)
mouse.click(Button.left, 1)
time.sleep(1.5)
mouse.position = (904, 181)
mouse.press(Button.left)
for number in range (80):
keyboard.press(Key.left)
keyboard.release(Key.left)
mouse.release(Button.left)
print("done")
Related
I am trying to make a windows analog of the Chat-wheel from Dota 2 or Battlefield with some fast commands like this.
How it should be:
While the G-key is pressed - the wheel with some sections appears at the centre of the screen, with the mouse centered on it and if I move the mouse to side_1 and then release the G-key -> func_1 executes.
If it was on side_2 -> func_2.
If I release the G-key at the centre -> wheel disappears and nothing happens.
So to monitor the X Y coordinates of the mouse I use following code:
from pynput import mouse
def on_move(x, y):
print(x, y)
# Collect events until released
with mouse.Listener(on_move=on_move) as listener:
listener.join()
It is spamming coordinates when I move the mouse.
But I am stuck in the part where i need:
to start the listener from another .py file and take these coordinates for the visual part of the program (like highlight the side of the wheel with command descriptions),
to close the listener from another .py file and take the last coordinates of the mouse when the G-key is released to compare with tge range of coordinates prescribed for functions.
You want something like this:
from pynput import mouse, keyboard
import time
def on_press(key):
print("pressed {}".format(key))
def on_release(key):
print("released {}".format(key))
def on_move(x,y):
print((x,y))
mouse_listener = mouse.Listener(
on_move=on_move)
mouse_listener.start()
key_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
key_listener.start()
# prevent the script from exiting immediately
time.sleep(10)
import time
import keyboard
from pynput.mouse import Controller
def get_xy():
mouse = Controller()
mouse_coord = str(mouse.position)
mouse_coord = mouse_coord.replace("(", "")
mouse_coord = mouse_coord.replace(")", "")
mouse_coord = mouse_coord.replace(",", "")
mouse_coord = mouse_coord.split(" ")
mouse_x = int(mouse_coord[0])
mouse_y = int(mouse_coord[1])
print(mouse_x, mouse_y)
while True:
if keyboard.is_pressed('b'):
get_xy()
time.sleep(0.01)
Output example: 654 326
So I'm trying to make the program not run in an endless loop once pressed is true and check for when the mouse button is released and stop the while loop.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
def on_click(x, y, button, pressed):
print('Pressed' if pressed else 'Released')
while (pressed):
m.move(0, 1)
time.sleep(.001)
with mouse.Listener(
on_click=on_click) as listener:
listener.join()
Something like this. Don't try to sleep for 1ms, you'll waste too many resources.
from pynput import mouse
from pynput.mouse import Button, Controller
import time
m = Controller()
mousedown = False
def on_click(x, y, button, pressed):
global mousedown
print('Pressed' if pressed else 'Released')
mousedown = pressed
listener = mouse.Listener(on_click=on_click)
while True:
if mousedown:
m.move( 0, 1 )
time.sleep( 0.1 )
I'm trying to detect what mouse button was clicked
so here is my code:
from pynput.mouse import Listener
def on_click(button, pressed):
if button.Left and pressed:
print("You pressed the left mouse button")
if button.Right and pressed:
print("You pressed the right mouse button")
so there was no errors but It's not working any Ideas?
From the Documentation Here
CODE
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format(
(x, y)))
def on_click(x, y, button, pressed):
print(button) # Print button to see which button of mouse was pressed
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
# Collect events until released
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_click=on_click)
listener.start()
As you can see, the button parameter in the function on_click tells you which button was pressed.
EDIT:
Here is how you may handle action based on which button of the mouse was pressed
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
print('Left if Pressed')
# ====== < Handle Pressed or released Event ====== > #
if pressed:
print('Do somethin when Pressed with LEft')
else:
print('LEFT is Released')
elif btn == 'right':
print('Right BTN was pressed ')
# ====== < Handle Pressed or released Event ====== > #
if not pressed:
print('right Button is released')
else:
pass
I post a second answer because of a different nature of the issue found on code here
The issue is how you call the imports.
CORRET CODE
from pynput import mouse
mouse_ = mouse.Controller()
button = mouse.Button
def on_click(x, y, button, pressed):
btn = button.name
if btn == 'left':
if pressed:
mouse_.click(button_.left)
print('works')
with mouse.Listener(
on_click=on_click
) as listener:
listener.join()
Copy and Paste the code without changes.
WARNING
when I use button.left my pc becomes extremely lagy so i suggest you to don't use is unless you know what you are doing
I made this little autofarm bot for GT since I was bored, but problem is, that I don't have any way of stopping it other than Task Manager. So I was thinking, is there a way for my program to detect if any key is pressed down no matter what window is on foreground?
Here is the code I am using right now:
import pyautogui
import sys
from pynput.mouse import Controller
from sys import exit
from time import sleep
from msvcrt import getch
mouse = Controller()
move = int()
move = 0
collections = int()
collections = 0
input("Hover your mouse over FIRST BLOCK and press ENTER.")
b1 = mouse.position
input("Hover your mouse over SECOND BLOCK and press ENTER.")
b2 = mouse.position
input("Hover your mouse over PUNCH and press ENTER.")
p = mouse.position
input("Hover your mouse over COLLECT moving direction and press ENTER.")
c1 = mouse.position
input("Hover your mouse over RETURN moving direction and press ENTER.")
c2 = mouse.position
pt = float(input("Insert punch TIME (ftank 1.0; pepper 1.2; pball 2.6)"))
try:
while True:
pyautogui.click(b1)#Block 1
pyautogui.dragTo(b2, duration = 0.25)#Block 2
pyautogui.mouseDown(p)#Punch
print("Punch Start.")
sleep(pt)
pyautogui.mouseUp()#Stop Punch
move = move + 1 #Count loops
print("Loop ", move, " Complete.")
if move >= 150: #Gem Collection
print("Collecting...")
pyautogui.mouseDown(c1) #Collect Gems
sleep(0.137)
print("Finished.")
pyautogui.mouseDown(c2) #Return to original position
sleep(0.8)
pyautogui.mouseUp()#Stop Moving
move = 0 #Reset Counter
collections = collections + 1
print("Finished ", collections,". Collecting Loop.")
except KeyboardInterrupt:
sys.exit()
I'm trying to build a short script in Python, where if the mouse is clicked, the mouse will reset to some arbitrary position (right now the middle of the screen).
I'd like this to run in the background, so it could work with other applications (most likely Chrome, or some web browser). I'd also like it so that a user could hold down a certain button (say CTRL) and they could click away and not have the position reset. This way they could close the script without frustration.
I'm pretty sure I know how to do this, but I'm not sure which library to use. I'd prefer if it was cross-platform, or at least work on Windows and Mac.
Here's my code so far:
#! python3
# resetMouse.py - resets mouse on click - usuful for students with
# cognitive disabilities.
import pymouse
width, height = m.screen_size()
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2
m = PyMouse()
k = PyKeyboard()
def onClick():
m.move(midWidth, midHeight)
try:
while True:
# if button is held down:
# continue
# onClick()
except KeyboardInterrupt:
print('\nDone.')
Try this
from pynput.mouse import Listener
def on_move(x, y):
print(x, y)
def on_click(x, y, button, pressed):
print(x, y, button, pressed)
def on_scroll(x, y, dx, dy):
print(x, y, dx, dy)
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
The following code worked perfectly for me. Thanks to Hasan's answer.
from pynput.mouse import Listener
def is_clicked(x, y, button, pressed):
if pressed:
print('Clicked ! ') #in your case, you can move it to some other pos
return False # to stop the thread after click
with Listener(on_click=is_clicked) as listener:
listener.join()
I was able to make it work just with win32api. It works when clicking on any window.
import win32api
import time
width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)
state_left = win32api.GetKeyState(0x01) # Left button up = 0 or 1. Button down = -127 or -128
while True:
a = win32api.GetKeyState(0x01)
if a != state_left: # Button state changed
state_left = a
print(a)
if a < 0:
print('Left Button Pressed')
else:
print('Left Button Released')
win32api.SetCursorPos((midWidth, midHeight))
time.sleep(0.001)
I was able to make it work for Windows using pyHook and win32api:
import win32api, pyHook, pythoncom
width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = (width + 1) / 2
midHeight = (height + 1) / 2
def moveCursor(x, y):
print('Moving mouse')
win32api.SetCursorPos((x, y))
def onclick(event):
print(event.Position)
moveCursor(int(midWidth), int(midHeight))
return True
try:
hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsUp(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
except KeyboardInterrupt:
hm.UnhookMouse()
print('\nDone.')
exit()