Accessing keyboard key up and key down - python

I was trying to create a simple program in python that can detect if a specific key on keyboard is pressed. As the response, I want my code to pressed a specific key on keyboard. I tested this code by pressing the W, A ,S ,D keys on a blank notepad document. I was expecting the result to be like wr, ar, sr, and dr. But the actual result that I got was rw, ra, rs ,rd. Can someone help me on this please?
import pythoncom, pyHook
import win32api, win32con
import time
import sys
import win32com.client
def OnKeyboardEvent(event):
if(event.Key=='A' or event.Key=='W' or event.Key=='D' or event.Key=='S'):
#key down for the R button
win32api.keybd_event(0x52,0,2,0)
#key up for the R button
win32api.keybd_event(0x52,0,0,0)
# create a hook manager
hm = pyHook.HookManager()
# watch for all mouse events
hm.KeyDown = OnKeyboardEvent
# set the hook
hm.HookKeyboard()
# wait forever
pythoncom.PumpMessages()

Related

Making an autoclicker in python?

I have designed this simple autoclicker in python using the pynput library
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()
def on_press(key):
global activated
if key == TOGGLE_KEY:
activated = not activated
while activated:
mouse.click(Button.left, 1)
time.sleep(0.01)
listner = Listener(on_press=on_press)
listner.start()
input()
This code activates a listner and when the user presses any key it calls the on_press function which checks if the button is equal to 't' then it inverts the property of activated and starts the while loop
I tried the above code and it worked but when I pressed 't' again the autoclicker did not switch off
I believe you are stuck in your while activated: loop. Pushing T again does not make the function run again unless the first function has stopped. A simple solution would be to put the click event in its own thread.
import time
import threading
from pynput.mouse import Button, Controller
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="t")
activated = False
mouse = Controller()
def on_press(key):
global activated
if key == TOGGLE_KEY:
activated = not activated
def doClick():
global activated
while True:
if activated:
mouse.click(Button.left, 1)
time.sleep(0.01)
threading.Thread(target = doClick).start()
listner = Listener(on_press=on_press)
listner.start()
input()
I think the problem is that the program is stuck in the loop. A solution I found is to use a thread
import threading
import time
from pynput.keyboard import Listener, KeyCode
from pynput.mouse import Controller
mouse = Controller()
class Clicker(threading.Thread):
__TOGGLE_KEY = KeyCode(char="t")
__activated = False
def run(self) -> None:
super().run()
while True:
if self.__activated:
# mouse.click(Button.left, 1)
time.sleep(1)
print("activated")
def keyboard_listener(self, key) -> None:
if key == self.__TOGGLE_KEY:
self.__activated = not self.__activated
clicker = Clicker()
listner = Listener(on_press=clicker.keyboard_listener)
listner.start()
clicker.start()
print("Listener started")
input()

Roblox won't detect mouse movement from autopygui

I am trying to create a script that automatically rejoins a roblox game on disconnect. I have beeen using ctypes to obtain a pixel on the screen, and if the pixel matches a color, it should automatically press the rejoin button. the problem is that it wont press the button. After some troubleshooting, I have figured out that the mouse movement wont register with the game, as if I move my mouse manually, it clicks the button.
In short, the game won't detect mouse movement from autopygui. If I move my mouse manually, it registers.
Video example:
https://youtu.be/VvAfHHXul8Q
Code:
import pyautogui as py
import keyboard
import tkinter
import requests
from ctypes import windll
from time import sleep
key = "m"
toggled = False
rjcolor = 16777215
root = tkinter.Tk()
root.withdraw()
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
dc= windll.user32.GetDC(0)
def getpixel(x,y):
return windll.gdi32.GetPixel(dc,x,y)
while True:
if keyboard.is_pressed(key):
toggled = not toggled
print("toggled to " + str(toggled))
sleep(0.5)
if toggled == True:
py.moveTo(width / 2, 800)
py.click(button='left')
if getpixel(1050, 600) == rjcolor:
print("disconnected, waiting until internet back online!")
while True:
try:
requests.head("http://www.google.com/", timeout=3)
print('The internet connection is active, rejoining.')
py.moveTo(1050, 590)
py.mouseDown(button='left')
sleep(0.1)
py.mouseUp(button='left')
break
except requests.ConnectionError:
print("The internet connection is down")
sleep(3)
sleep(0.1)
Pyautogui has issues with clicking on roblox, but i've found a workaround:
Replace py.click(button="left") with autoit.mouse_click("left")
import autoit
autoit.mouse_click("left")

Why do I always have the error message Controller has no attribute is_pressed?

I've been coding a very simple autoclicker. My autoclicker works just fine, but the only way to kill it is forcefully shut down my computer because it clicks so fast I can't access my taskbar. I could make it slower, but I'd prefer a way for the user to close the autoclicker with the press of a button. I've tried if keyboard.is_presssed('q'): break but I always get the error message AttributeError: 'Controller' object has no attribute 'is_pressed'. Did you mean: 'alt_pressed'? I expected my code to break the loop when I press q, but instead I get an error message. The error message will also pop up without the pressing of q. My code as of now is:
from pynput.mouse import Button, Controller
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
mouse = Controller()
while True:
time.sleep(10)
mouse.click(Button.left)
if keyboard.is_pressed('q'):
break
pynput doesn't have is_pressed() - I don't know where you find it.
You should rather use pynput.keyboard.Listener to run code when q is pressed and set some variable - q_is_pressed = True - or run code which ends program.
You can't have two objects with the same name Controller.
One Controller replaces other Controller and later you use the same Controller to create mouse and keyboard - and this makes problem.
You have to use pynput.mouse.Controller and pynput.keyboard.pynput.Controller
import pynput
from pynput.mouse import Button
from pynput.keyboard import Key
import time
keyboard = pynput.keyboard.Controller()
mouse = pynput.mouse.Controller()
while True:
time.sleep(10)
mouse.click(Button.left)
#if keyboard.is_pressed('q'): # <-- this will need Listener()
# break
EDIT:
To end code when q was pressed you have to use Listener
For example:
import pynput
from pynput.mouse import Button
import time
mouse_controller = pynput.mouse.Controller()
def on_press(key):
print('pressed:', key)
if str(key) == "'q'": # it has to be with `' '` inside `" "`
# Stop listener
print("exit listener")
return False # `False` ends listener
with pynput.keyboard.Listener(on_press=on_press) as keyboard_listener:
while keyboard_listener.is_alive():
time.sleep(10)
mouse_controller.click(Button.left)
print('clicked')

Simulate real click python

As I can simulate a click as if it were made from the mouse, a game has detection of click events or simulated keys, I would like to know if it is possible to simulate a real click.
Translated.
My code:
import time
import keyboard
import pyautogui
from playsound import playsound
pyautogui.PAUSE = 0.2
sW, sH = pyautogui.size()
down = False
while True:
if keyboard.is_pressed('f4'):
if not down:
down = True
playsound('on.mp3')
pyautogui.moveTo(sW*0.67, sH*0.5)
pyautogui.click()
pyautogui.moveTo(sW*0.67, sH*0.6)
pyautogui.click()
pyautogui.moveTo(sW*0.67, sH*0.64)
else:
down = False
This code simulates a real click of the mouse.
import win32api, win32con
from time import sleep
def click(x,y, duration=30, delay=0.3):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
sleep(duration / 1000)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
sleep(delay)
Why?
Because the lib win32api is directly connected with the windows commands.
When u click with the mouse, you actualy triggers a function inside the windows.
win32api does de same.
Also...win32api is the fastest comunication with the windows for this stuff, like image rendering

hook the left mouse button down event on any window

I want to hook the left mouse button down event on any window, my code as following :
import win32gui
import win32ui
import win32con
def onMousePressed(self):
print('onMousePressed', win32gui.GetCursorPos())
def listener():
windowHandle = win32gui.WindowFromPoint(win32gui.GetCursorPos())
clickedWindow = win32ui.CreateWindowFromHandle(windowHandle)
clickedWindow.HookMessage(onMousePressed, win32con.WM_LBUTTONDOWN)
# print('-------------registerMouseEvent', clickedWindow)
while True:
listener()
However , the onMousePressed function was never called when clicked, what is wrong ?
P.S. I know some similar projects such as PyUserInput, mouse, pynput, just want to know why my code didn't work.

Categories