Last active
August 10, 2016 04:42
-
-
Save sean-lin/1d8aec5554060f06e95160553b4d7109 to your computer and use it in GitHub Desktop.
python windows auto click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import time | |
import win32con | |
import win32api | |
import ctypes | |
from ctypes import wintypes | |
byref = ctypes.byref | |
user32 = ctypes.windll.user32 | |
def clicker(x,y): | |
"""Clicks on given position x,y | |
Input: | |
x -- Horizontal position in pixels, starts from top-left position | |
y -- Vertical position in pixels, start from top-left position | |
""" | |
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) | |
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) | |
def auto_clicker(x = -1,y = -1): | |
"""Keep clicking on position x,y. If no input is given, gets from actual | |
mouse position. | |
""" | |
if x == -1 | y == -1: | |
x,y = win32api.GetCursorPos() | |
clicker(x,y) | |
HOTKEYS = { | |
1: (win32con.VK_F5, win32con.MOD_WIN), | |
2: (win32con.VK_F6, win32con.MOD_WIN), | |
3: (win32con.VK_F7, win32con.MOD_WIN), | |
} | |
for id, (vk, modifiers) in HOTKEYS.items(): | |
print("Registering id", id, "for key", vk) | |
if not user32.RegisterHotKey(None, id, modifiers, vk): | |
print("Unable to register id", id) | |
def main(): | |
start_click = False | |
try: | |
msg = wintypes.MSG() | |
t = user32.SetTimer(None, None, 100, None) | |
while user32.GetMessageA(byref(msg), None, 0, 0) != 0: | |
if msg.message == win32con.WM_HOTKEY: | |
action = int(msg.wParam) | |
if action == 1: | |
print 'start' | |
start_click = True | |
elif action == 2: | |
print 'end' | |
start_click = False | |
elif action == 3: | |
print 'exit' | |
break | |
if msg.message == win32con.WM_TIMER and start_click: | |
auto_clicker() | |
user32.TranslateMessage(byref(msg)) | |
user32.DispatchMessageA(byref(msg)) | |
finally: | |
user32.KillTimer(None, t) | |
for id in HOTKEYS.keys(): | |
user32.UnregisterHotKey(None, id) | |
print("user32.UnregisterHotKey (None, id)") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment