Python 模拟鼠标操作 干久了程序员多少都会有使用鼠标的手感觉不适的时候,所以就会换一下手来使鼠标,但是每次换来换去很麻烦,所以我写了一段Python的小程序,操作鼠标移动和点击,来完成交换鼠标按键的操作。代码如下: imp imp imp imp from ctypes imp ##open mouse properties process = subprocess.Popen("control.exe main.cpl") time.sleep(1) pwin = win32gui.FindWindow(0,'Mouse Properties') text = win32gui.GetWindowText(pwin) print(text) def _windowEnumerationHandler(hwnd, resultList): '''Pass to win32gui.EnumWindows() to generate list of window handle, window text, window class tuples.''' ##print(win32gui.GetWindowText(hwnd)) resultList.append((hwnd, win32gui.GetWindowText(hwnd), win32gui.GetClassName(hwnd))) windows = [] win32gui.EnumChildWindows(pwin, _windowEnumerationHandler, windows) isRight = 0 def ClickChildControl(hwnd): (left, top, right, bottom) = win32gui.GetWindowRect(hwnd) print(left,top,right,bottom) windll.user32.SetCursorPos(left + (right - left)/2, top + (bottom - top)/2) time.sleep(0.5) if isRight: win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, 0, 0) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, 0, 0) time.sleep(0.05) else: win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) time.sleep(0.05) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) time.sleep(0.05) wantText = "Switch primary and secondary buttons" for hwnd, windowText, windowClass in windows: if wantText in windowText: print('switch') isRight = win32gui.SendMessage(hwnd, win32con.BM_GETCHECK, 0, 0) ClickChildControl(hwnd) isRight = not isRight for hwnd, windowText, windowClass in windows: if 'OK' in windowText: print('Get Ok') ClickChildControl(hwnd) 在Windows XP2 英文, Python 2.6上测试通过。 |
|