您的位置:首页 > 编程语言 > Python开发

Python 模拟鼠标操作

2013-02-06 06:36 465 查看

Python 模拟鼠标操作

2009-09-13 21:49:44| 分类:

python |字号 订阅

Python 模拟鼠标操作
干久了程序员多少都会有使用鼠标的手感觉不适的时候,所以就会换一下手来使鼠标,但是每次换来换去很麻烦,所以我写了一段Python的小程序,操作鼠标移动和点击,来完成交换鼠标按键的操作。代码如下:
import subprocess
import win32ui,win32con,pythoncom,win32gui,win32process,win32api
import time
import string
from ctypes import *
##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上测试通过。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: