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
Related
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")
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 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 save the mouse's x and y coordinates when the mouse button is pressed and, separately, when it is released. I am able to print them but unable to save them to variables.
Here's what I got:
from pynput.mouse import Listener
def on_click(x, y, button, pressed):
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
with Listener(on_click=on_click) as listener:
listener.join()
And then how would I call these variables on a global scale to use with another module (e.g. pyautogui?)
You've got pretty much everything in place, so I only had to add a few lines. Globals aren't the very best way to do things, but since this program isn't too complex, they will do the job.
The initial values of down_x, etc. don't really matter, as they will be overwritten, but they have to be there, or Python will throw an error.
#if you want to delay between mouse clicking, uncomment the line below
#import time
from pynput.mouse import Listener
import pyautogui
down_x = down_y = up_x = up_y = -1
def on_click(x, y, button, pressed):
global down_x
global down_y
global up_x
global up_y
if pressed:
(down_x, down_y) = (x, y)
else:
(up_x, up_y) = (x, y)
return False
with Listener(on_click=on_click) as listener:
listener.join()
print("Mouse drag from", down_x, ",", down_y, "to", up_x, ",", up_y)
# you may wish to import the time module to make a delay
#time.sleep(1)
pyautogui.mouseDown(down_x, down_y)
#time.sleep(1)
pyautogui.mouseUp(up_x, up_y)
Use global variables:
from pynput.mouse import Listener
xx, yy = 0, 0
def on_click(x, y, button, pressed):
global xx, yy
xx, yy = x, y
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
if not pressed:
# Stop listener
return False
with Listener(on_click=on_click) as listener:
listener.join()
# here you can read xx and yy
If your code gets more complicated you can consider wrapping it up in a class.
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()