def start(self): while self._running: b, msg = win32gui.GetMessage(0, 0, 0) if not msg: break win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg)
def wait_for_hotkeys(): def handle_windows(nCode, wParam, lParam): isKeyDown = False isKeyUp = False if wParam == win32con.WM_KEYDOWN or wParam == win32con.WM_SYSKEYDOWN: isKeyDown = True if wParam == win32con.WM_KEYUP or wParam == win32con.WM_SYSKEYUP: isKeyUp = True shouldContinue = True if isKeyDown or isKeyUp: shouldContinue = not handle_python(isKeyDown, lParam[0], lParam[1]) if shouldContinue: return windll.user32.CallNextHookEx(windowsHook, nCode, wParam, lParam) return 1 HANDLER = CFUNCTYPE(c_uint, c_uint, c_uint, POINTER(c_uint)) handlerPtr = HANDLER(handle_windows) setWindowsHookExA = windll.user32.SetWindowsHookExA setWindowsHookExA.argtypes = (wintypes.DWORD, HANDLER, wintypes.HINSTANCE, wintypes.DWORD) windowsHook = setWindowsHookExA(win32con.WH_KEYBOARD_LL, handlerPtr, windll.kernel32.GetModuleHandleW(None), 0) atexit.register(windll.user32.UnhookWindowsHookEx, windowsHook) while not pylewm.commands.stopped: msg = win32gui.GetMessage(None, 0, 0) win32gui.TranslateMessage(byref(msg)) win32gui.DispatchMessage(byref(msg))
def listen(): """ Calls `handlers` for each keyboard event received. This is a blocking call. """ # Adapted from http://www.hackerthreads.org/Topic-42395 from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref import win32con, win32api, win32gui, atexit event_types = { win32con.WM_KEYDOWN: 'key down', win32con.WM_KEYUP: 'key up', 0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key. 0x105: 'key up', # WM_SYSKEYUP, used for Alt key. } def low_level_handler(nCode, wParam, lParam): """ Processes a low level Windows keyboard event. """ event = KeyboardEvent(event_types[wParam], lParam[0], lParam[1], lParam[2] == 32, lParam[3]) for handler in handlers: handler(event) # Be a good neighbor and call the next hook. return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam) def low_level_mouse_handler(nCode, wParam, lParam): event = MouseEvent(MSG_TEXT.get(wParam, str(wParam)), lParam[0], lParam[1], lParam[2] == 32, lParam[3]) if wParam == win32con.WM_LBUTTONDOWN: print('Click here') for handler in handlers: handler(event) # Be a good neighbor and call the next hook. return windll.user32.CallNextHookEx(mouse_hook_id, nCode, wParam, lParam) # Our low level handler signature. CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) # Convert the Python handler into C pointer. pointer = CMPFUNC(low_level_handler) mouse_pointer = CMPFUNC(low_level_mouse_handler) # Hook both key up and key down events for common keys (non-system). hook_id = windll.user32.SetWindowsHookExW(win32con.WH_KEYBOARD_LL, pointer, None, 0) mouse_hook_id = windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, mouse_pointer, None, 0) # Register to remove the hook when the interpreter exits. Unfortunately a # try/finally block doesn't seem to work here. atexit.register(windll.user32.UnhookWindowsHookEx, hook_id) while True: msg = win32gui.GetMessage(None, 0, 0) win32gui.TranslateMessage(byref(msg)) win32gui.DispatchMessage(byref(msg))
def dispatchMessage(winid): import win32api,win32gui,win32con status, msg = win32gui.PeekMessage(winid,0,0,win32con.PM_NOREMOVE) if not msg[0] == 0: b,msg = win32gui.GetMessage(winid,0,0) if msg: win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg)
def keepAlive(self): if self.kbHook is None: return msg = win32gui.GetMessage(None, 0, 0) while msg and self.kbHook is not None: win32gui.TranslateMessage(byref(msg)) win32gui.DispatchMessage(byref(msg)) msg = win32gui.GetMessage(None, 0, 0)
def mainloop(self): while True: code, msg = win32gui.GetMessage(0, 0, 0) if not code: break if code < 0: error = win32api.GetLastError() raise RuntimeError(error) ####################################### ### Trio specific part of main loop ### ####################################### hwnd, msgid, lparam, wparam, time, point = msg if hwnd == win32con.NULL and msgid == TRIO_MSG: do_trio() continue ############################### ### Trio specific part ends ### ############################### win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg)
def main(): global DEBUG_IMAGE global hWindow """Runs the entire program. The Kings Raid Program must be on the desktop (not minimized) but can run in the background while you do other things""" logging.debug('Program Started. Press F12 to abort at any time.') getGameRegion() loadImages() initDebugOverlay() #cv2.startWindowThread() #cv2.namedWindow("debug") while True: status, msg = win32gui.PeekMessage(hWindow, 0, 0, win32con.PM_REMOVE) if (status): win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg) else: not processInput() processScreen() mainLogic() #cv2.imshow("debug", DEBUG_IMAGE) cv2.destroyAllWindows()
def _run_window(self): # Create hidden window log.debug('_run_window start') wc = win32gui.WNDCLASS() wc.lpszClassName = 'devicenotify' wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW wc.hbrBackground = win32con.COLOR_WINDOW + 1 wc.lpfnWndProc = self.window_callback class_atom = win32gui.RegisterClass(wc) if not class_atom: log.error('window class not created') return self._hwnd = win32gui.CreateWindow(wc.lpszClassName, 'devicenotify', win32con.WS_CAPTION, 100, 100, 900, 900, 0, 0, 0, None) if not self._hwnd: log.error('window not created') return # Watch for all USB device notifications devfilt = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE( GUID_DEVINTERFACE_USB_DEVICE) self._event = win32gui.RegisterDeviceNotification( self._hwnd, devfilt, win32con.DEVICE_NOTIFY_WINDOW_HANDLE) while 1: b, msg = win32gui.GetMessage(None, 0, 0) log.debug('win32_device_notify message') if not b or not msg: break win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg) win32gui.UnregisterDeviceNotification(self._event) win32gui.UnregisterClass(wc.lpszClassName, None) self._hwnd = None log.debug('_run_window done')
def start(self, asynchronous=True): if asynchronous: print('async hook') import threading threading.Thread(target=self.start, kwargs={ 'asynchronous': False }).start() return print('starting hook') import win32con keyboard_event_types = { win32con.WM_KEYDOWN: 'key down', win32con.WM_KEYUP: 'key up', 0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key. 0x105: 'key up', # WM_SYSKEYUP, used for Alt key. } mouse_event_types = { win32con.WM_RBUTTONDOWN: 'RMB down', win32con.WM_RBUTTONUP: 'RMB up', win32con.WM_MOUSEMOVE: 'mouse move' } def low_level_keyboard_handler(nCode, wParam, lParam): event = (nCode, self.KeyboardEvent(keyboard_event_types[wParam], lParam[0], lParam[1], lParam[2] == 32, lParam[3])) # Be a good neighbor and call the next hook. if self.keyboard_callback(event): return ctypes.windll.user32.CallNextHookEx( self.hook_id_keyboard, nCode, wParam, lParam) else: print("#") return 1 def low_level_mouse_handler(nCode, wParam, lParam): event = (nCode, mouse_event_types.get(wParam, 'unknown')) if self.mouse_callback(event): # Be a good neighbor and call the next hook. return ctypes.windll.user32.CallNextHookEx( self.hook_id_mouse, nCode, wParam, lParam) else: return 1 import ctypes CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)) # Convert the Python handler into C pointer. pointer_keyboard = CMPFUNC(low_level_keyboard_handler) pointer_mouse = CMPFUNC(low_level_mouse_handler) import win32api # Hook both key up and key down events for common keys (non-system). self.hook_id_keyboard = ctypes.windll.user32.SetWindowsHookExA( win32con.WH_KEYBOARD_LL, pointer_keyboard, win32api.GetModuleHandle(None), 0) self.hook_id_mouse = ctypes.windll.user32.SetWindowsHookExA( win32con.WH_MOUSE_LL, pointer_mouse, win32api.GetModuleHandle(None), 0) # Register to remove the hook when the interpreter exits. Unfortunately a # try/finally block doesn't seem to work here. import atexit atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, self.hook_id_keyboard) atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, self.hook_id_mouse) while True: import win32gui #peek_result, msg = win32gui.PeekMessage(None, 0, 0, 1) result, msg = win32gui.GetMessage(None, 0, 0) print('got msg:', msg) win32gui.TranslateMessage(msg) #print('translated') win32gui.DispatchMessage(msg) #print('sent') #sleep(0.5) pass
def init_keyboard_listener(self): from ctypes import CFUNCTYPE, c_int, POINTER, Structure from ctypes.wintypes import DWORD, WPARAM, LPARAM class WindowsKeyEvent(AdHocStruct): pass class KBDLLHOOKSTRUCT(Structure): _fields_ = [ ("vk_code", DWORD), ("scan_code", DWORD), ("flags", DWORD), ("time", c_int), ] DOWN = [win32con.WM_KEYDOWN, win32con.WM_SYSKEYDOWN] #UP = [win32con.WM_KEYUP, win32con.WM_SYSKEYUP] ALL_KEY_EVENTS = { win32con.WM_KEYDOWN: "KEYDOWN", win32con.WM_SYSKEYDOWN: "SYSKEYDOWN", win32con.WM_KEYUP: "KEYUP", win32con.WM_SYSKEYUP: "SYSKEYUP", } def low_level_keyboard_handler(nCode, wParam, lParam): try: scan_code = lParam.contents.scan_code focused = self.client._focused keyname = { win32con.VK_LWIN: "Super_L", win32con.VK_RWIN: "Super_R", }.get(scan_code) keycode = 0 modifiers = [] kh = self.client.keyboard_helper if focused and keyname and kh and kh.keyboard and wParam in ALL_KEY_EVENTS: modifier_keycodes = kh.keyboard.modifier_keycodes modifier_keys = kh.keyboard.modifier_keys #find the keycode: (try the exact key we hit first) for x in (keyname, "Super_L", "Super_R"): keycodes = modifier_keycodes.get(x, []) for k in keycodes: #only interested in numeric keycodes: try: keycode = int(k) break except: pass if keycode > 0: break for vk, modkeynames in { win32con.VK_NUMLOCK: ["Num_Lock"], win32con.VK_CAPITAL: ["Caps_Lock"], win32con.VK_CONTROL: ["Control_L", "Control_R"], win32con.VK_SHIFT: ["Shift_L", "Shift_R"], }.items(): if win32api.GetKeyState(vk): for modkeyname in modkeynames: mod = modifier_keys.get(modkeyname) if mod: modifiers.append(mod) break #keylog.info("keyboard helper=%s, modifier keycodes=%s", kh, modifier_keycodes) keylog( "scan_code=%s, event=%s, keyname=%s, keycode=%s, modifiers=%s, focused=%s", scan_code, ALL_KEY_EVENTS.get(wParam), keyname, keycode, modifiers, focused) if keycode > 0: key_event = WindowsKeyEvent() key_event.keyname = keyname key_event.pressed = wParam in DOWN key_event.modifiers = modifiers key_event.keyval = scan_code key_event.keycode = keycode key_event.string = "" key_event.group = 0 keylog("detected windows key, sending %s", key_event) self.client.keyboard_helper.send_key_action( focused, key_event) #swallow this event: return 1 except Exception as e: keylog.error("Error: low level keyboard hook failed") keylog.error(" %s", e) return windll.user32.CallNextHookEx(keyboard_hook_id, nCode, wParam, lParam) # Our low level handler signature. CMPFUNC = CFUNCTYPE(c_int, WPARAM, LPARAM, POINTER(KBDLLHOOKSTRUCT)) # Convert the Python handler into C pointer. pointer = CMPFUNC(low_level_keyboard_handler) # Hook both key up and key down events for common keys (non-system). keyboard_hook_id = windll.user32.SetWindowsHookExA( win32con.WH_KEYBOARD_LL, pointer, win32api.GetModuleHandle(None), 0) # Register to remove the hook when the interpreter exits: keylog("init_keyboard_listener() hook_id=%#x", keyboard_hook_id) while True: msg = win32gui.GetMessage(None, 0, 0) keylog("init_keyboard_listener: GetMessage()=%s", msg) win32gui.TranslateMessage(byref(msg)) win32gui.DispatchMessage(byref(msg))
def start(self, asynchronous=True): if asynchronous: print('async hook') t = threading.Thread(target=self.start, kwargs={'asynchronous': False}) self.running = True t.start() return t print('starting hook') keyboard_event_types = { win32con.WM_KEYDOWN: 'key down', win32con.WM_KEYUP: 'key up', 0x104: 'key down', # WM_SYSKEYDOWN, used for Alt key. 0x105: 'key up', # WM_SYSKEYUP, used for Alt key. } # WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_MOUSEHWHEEL, WM_RBUTTONDOWN, or WM_RBUTTONUP. mouse_event_types = { win32con.WM_RBUTTONDOWN: 'RMB down', win32con.WM_RBUTTONUP: 'RMB up', win32con.WM_LBUTTONDOWN: 'LMB down', win32con.WM_LBUTTONUP: 'LMB up', 0x0207: 'MMB down', 0x0208: 'MMB up', win32con.WM_MOUSEWHEEL: 'Wheel', 0x020E: 'Horizontal Wheel', # win32con.WM_MOUSEHWHEEL win32con.WM_MOUSEMOVE: 'mouse move' } def low_level_keyboard_handler(nCode, wParam, lParam): event = (nCode, self.KeyboardEvent( event_type=keyboard_event_types[wParam], key_code=lParam[0] & 0xFFFFFFFF, scan_code=lParam[1] & 0xFFFFFFFF, alt_pressed=lParam[2] == 32, time=lParam[3] & 0xFFFFFFFF if lParam[3] is not None else 0, extra_info=lParam[4])) # unsigned int 64 for 32bit # Be a good neighbor and call the next hook. if self.keyboard_callback(event): return ctypes.windll.user32.CallNextHookEx( self.hook_id_keyboard, nCode, wParam, lParam) else: print("#") return 1 def low_level_mouse_handler(nCode, wParam, lParam): event = (nCode, self.MouseEvent(event_type=mouse_event_types.get( wParam, f'unknown ({hex(wParam)})'), point=lParam[0], wheel_direction=lParam[1], injection=lParam[2], time=lParam[3])) if self.mouse_callback(event): # Be a good neighbor and call the next hook. return ctypes.windll.user32.CallNextHookEx( self.hook_id_mouse, nCode, wParam, lParam) else: return 1 CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)) # Convert the Python handler into C pointer. pointer_keyboard = CMPFUNC(low_level_keyboard_handler) pointer_mouse = CMPFUNC(low_level_mouse_handler) # Hook both key up and key down events for common keys (non-system). try: wh_keyboard_lo_level = win32con.WH_KEYBOARD_LL wh_mouse_low_level = win32con.WH_MOUSE_LL p_keyoard = pointer_keyboard p_mouse = pointer_mouse module_handle = win32api.GetModuleHandle(None) module_handle = 0 self.hook_id_keyboard = ctypes.windll.user32.SetWindowsHookExA( wh_keyboard_lo_level, p_keyoard, module_handle, 0) self.hook_id_mouse = ctypes.windll.user32.SetWindowsHookExA( wh_mouse_low_level, p_mouse, module_handle, 0) except Exception as ex: print(ex) # Register to remove the hook when the interpreter exits. # Unfortunately a # try/finally block doesn't seem to work here. atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, self.hook_id_keyboard) atexit.register(ctypes.windll.user32.UnhookWindowsHookEx, self.hook_id_mouse) while self.running: #peek_result, msg = win32gui.PeekMessage(None, 0, 0, 1) result, msg = win32gui.GetMessage(None, 0, 0) print('got msg:', msg, result) win32gui.TranslateMessage(msg) #print('translated') win32gui.DispatchMessage(msg) #print('sent') #sleep(0.5) pass
def listen(): def low_level_handler(nCode, wParam, lParam): global c_word global shift global other Key = lParam[0] & 0xffff if Key == 160 or Key == 161 or Key == 16: shift = True if wParam == WM_KEYDOWN else False if Key == 91 or Key == 92 or \ Key == 162 or Key == 163 or \ Key == 163 or Key == 164 or Key == 18: other = True if wParam == WM_KEYDOWN else False if wParam == WM_KEYDOWN: if(34 <= Key <= 40 or 44 <= Key <= 46 or Key == 145 or Key == 19 or Key == 13 or Key == 32) \ and not self: print("c_word Cleared!") c_word.clear() if Key == 8 and not self: if len(c_word) > 0: del c_word[-1] print( "removed 1 item from c_word,\nnow lenght is {}".format( len(c_word))) else: print("c_word is empty.") if(65 <= Key <= 90 or 48 <= Key <= 57 or 186 <= Key <= 192 or 219 <= Key <= 222) \ and not other and not self: kst = create_string_buffer(256) if not shift: print(ToUn(Key, 0, kst, lcs.GetCurrentLocale())) c_word.append(YuKey(Key, False)) else: kst[16] = 0xff print(ToUn(Key, 0, kst, lcs.GetCurrentLocale())) c_word.append(YuKey(Key, True)) return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam) CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) pointer = CMPFUNC(low_level_handler) hook_id = windll.user32.SetWindowsHookExA(WH_KEYBOARD_LL, pointer, w3a.GetModuleHandle(None), 0) def low_level_mouse_handler(nCode, wParam, lParam): if wParam == WM_LBUTTONUP or wParam == WM_RBUTTONUP: print('c_word Cleared!') c_word.clear() return windll.user32.CallNextHookEx(hook2_id, nCode, wParam, lParam) pointer2 = CMPFUNC(low_level_mouse_handler) hook2_id = windll.user32.SetWindowsHookExA(WH_MOUSE_LL, pointer2, w3a.GetModuleHandle(None), 0) atexit.register(windll.user32.UnhookWindowsHookEx, hook_id) while True: try: msg = w3g.GetMessage(None, 0, 0) w3g.TranslateMessage(brf(msg)) w3g.DispatchMessage(brf(msg)) except TypeError: HKHandle(msg[1][2])
def WinMain(self): hInstance = win32api.GetModuleHandle() wndClass = win32gui.WNDCLASS() wndClass.hInstance = hInstance wndClass.lpszClassName = self.szClassName wndClass.lpfnWndProc = self.WndProc wndClass.style = win32con.CS_DBLCLKS wndClass.hIcon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION) wndClass.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW) wndClass.cbWndExtra = 0 wndClass.hbrBackground = win32gui.GetStockObject(win32con.BLACK_BRUSH) tWnd = win32gui.FindWindow(0, self.TargetName) if tWnd == 0: exit(1) # 시작시 타켓윈도우 없으면 종료 # while tWnd == 0: # tWnd = win32gui.FindWindow(0, self.TargetName) # 타겟윈도우 찾을때까지 반복 tRect = win32gui.GetWindowRect(tWnd) wWidth = tRect[2] - tRect[0] wHeight = tRect[3] - tRect[1] if not tWnd: wWidth = 400 wHeight = 350 wndClassAtom = None try: wndClassAtom = win32gui.RegisterClass(wndClass) except Exception as e: print(e) raise e self.hWnd = win32gui.CreateWindowEx( win32con.WS_EX_TOPMOST | win32con.WS_EX_TRANSPARENT, wndClassAtom, "Overlay", win32con.WS_POPUP, 100, 90, wWidth, wHeight, 0, 0, hInstance, None) #hWnd # Show & update the window win32gui.ShowWindow(self.hWnd, win32con.SW_SHOW) win32gui.UpdateWindow(self.hWnd) win32gui.SetWindowLong( self.hWnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong(self.hWnd, win32con.GWL_EXSTYLE) ^ win32con.WS_EX_LAYERED) win32gui.SetLayeredWindowAttributes(self.hWnd, win32api.RGB(0, 0, 0), 0, win32con.LWA_COLORKEY) # win32ui.CreateThread(SetWindow, hWnd) t = threading.Thread(target=self.SetWindow, args=(self.hWnd, )) t.daemon = True t.start() #msg pump msg = win32gui.GetMessage(self.hWnd, 0, 0) msg = msg[1] while msg[1]: win32gui.TranslateMessage(msg) win32gui.DispatchMessage(msg) msg = win32gui.GetMessage(self.hWnd, 0, 0) msg = msg[1] if self.flag == True: exit(0)