分享

Python 模拟鼠标操作

 昵称3884271 2015-05-14

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上测试通过。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多