在python中控制鼠标

部署运行你感兴趣的模型镜像

一.在获得焦点的窗口中移动鼠标

#coding=gbk
from ctypes import *
import time

user32 = windll.user32
kernel32 = windll.kernel32

class RECT(Structure):
    _fields_ = [
    ("left", c_ulong),
    ("top", c_ulong),
    ("right", c_ulong),
    ("bottom", c_ulong)
    ]

class GUITHREADINFO(Structure):
    _fields_ = [
    ("cbSize", c_ulong),
    ("flags", c_ulong),
    ("hwndActive", c_ulong),
    ("hwndFocus", c_ulong),
    ("hwndCapture", c_ulong),
    ("hwndMenuOwner", c_ulong),
    ("hwndMoveSize", c_ulong),
    ("hwndCaret", c_ulong),
    ("rcCaret", RECT)
]

def moveCursorInCurrentWindow(x, y):
    # Find the focussed window.
    guiThreadInfo = GUITHREADINFO(cbSize=sizeof(GUITHREADINFO))
    user32.GetGUIThreadInfo(0, byref(guiThreadInfo))
    focussedWindow = guiThreadInfo.hwndFocus
   
    # Find the screen position of the window.
    windowRect = RECT()
    user32.GetWindowRect(focussedWindow, byref(windowRect))

    # Finally, move the cursor relative to the window.
    user32.SetCursorPos(windowRect.left + x, windowRect.top + y)
   

for i in range(0, 10):
    time.sleep(1)
    moveCursorInCurrentWindow(i * 15, i * 10)


二.移动鼠标

from ctypes import *

windll.user32.SetCursorPos(100, 100)


三.获得鼠标当前坐标

import win32gui

win32gui.GetCursorPos()


四.模拟鼠标点击

#coding=gbk

import win32api

import win32con

from ctypes import windll


#鼠标左键

win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y)

time.sleep(0.05)

win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y)


#鼠标右键

win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, x, y)

time.sleep(0.05)

win32api.mouse_event(win32con.MOUSEEVENTF_RIGHTUP, x, y)


五.获取鼠标事件

import win32con
import win32gui
import ctypes
from ctypes import wintypes

# container class for global hook
# this will store the HHOOK id and mouse information
class Hook:
    def __init__(self):
        self.hook = 0
        self.m_struct = None

class MSLLHOOKSTRUCT(ctypes.Structure):
    _fields_ = [("pt", wintypes.POINT),
                ("mouseData", ctypes.c_long),
                ("flags", ctypes.c_long),
                ("time", ctypes.c_long),
                ("dwExtraInfo", ctypes.POINTER(ctypes.c_ulong) )]

def CopyMemory( Destination, Source ):
    Source = ctypes.c_void_p(Source)
    ctypes.windll.kernel32.RtlMoveMemory(ctypes.addressof(Destination), Source, ctypes.sizeof(Destination))

def PostQuitMessage( nMsg ):
    return ctypes.windll.user32.PostQuitMessage(nMsg)

def GetModuleHandle( lpModuleName ):
    return ctypes.windll.kernel32.GetModuleHandleA(lpModuleName)

def CallNextHookEx( hhk, nCode, wParam, lParam ):
     return ctypes.windll.user32.CallNextHookEx(hhk, nCode, wParam, lParam)

def SetWindowsHookEx( idHook, lpFunc, hMod, dwThreadId ):
     WINFUNC = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_long, ctypes.c_long, ctypes.c_long)
     return ctypes.windll.user32.SetWindowsHookExA( idHook, WINFUNC(lpFunc), hMod, dwThreadId)

def UnhookWindowsHookEx( hhk ):
     return ctypes.windll.user32.UnhookWindowsHookEx(hhk)


# create instance of global mouse hook class
mll_hook = Hook()
mll_hook.m_struct = MSLLHOOKSTRUCT()

# mouse hook callback. intercept mouse events
def LowLevelMouseProc( nCode, wParam, lParam ):
   
    if nCode == win32con.HC_ACTION:     
        # lparam holds the starting address of the mouse hook structure
        # call copymemory so that m_struct class points to the mouse structure pool
        CopyMemory( mll_hook.m_struct, lParam )
        # print out the cursors x and y screen position
        if wParam == win32con.WM_MBUTTONUP:
            PostQuitMessage(0)  
            
        if wParam == win32con.WM_LBUTTONUP:    # WM_RBUTTONUP
            print "x = [%d]/ty = [%d]" % (mll_hook.m_struct.pt.x,mll_hook.m_struct.pt.y)
     
   
    return CallNextHookEx( mll_hook.hook, nCode, wParam, lParam )
     

if __name__ == '__main__':
    print "Press the middle mouse button to exit "
    try:
        mll_hook.hook = SetWindowsHookEx(win32con.WH_MOUSE_LL,
                                         LowLevelMouseProc,
                                         GetModuleHandle(0),
                                         0)
    except Exception, err:
        print err
    # set up a message queue, you can use any valid message loop tkinter, pygtk and wxpythons message loops all work
    win32gui.PumpMessages()
    # unhook the mouse hook
    UnhookWindowsHookEx(mll_hook.hook)

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think>我们要在Python控制鼠标点击,可以使用第三方库如`pyautogui`或`pynput`。这里我将展示使用`pyautogui`的方法,因为它更简单易用。 首先,需要安装pyautogui:`pip install pyautogui` 下面是一个示例代码,它将控制鼠标移动到指定位置并点击。 注意:使用pyautogui时,为了安全,我们通常设置一个安全措施,比如在程序开始运行时设置一个延迟,这样我们有时间把鼠标移动到屏幕角落(比如左上角)来触发FailSafeException从而终止程序。 代码功能:将鼠标移动到(100,100)的位置,然后进行左键点击。 另外,我们还可以设置点击的次数、间隔时间等。 但是请注意:在实际运行代码前,确保你知道如何终止程序(比如快速将鼠标移动到屏幕左上角可以触发异常退出),因为失控的鼠标控制可能会带来麻烦。 下面给出代码: </think>在 Python控制鼠标点击可以使用 `pyautogui` 库,它提供了跨平台的鼠标/键盘控制功能。以下是详细解决方案: ### 解决方案代码 ```python import pyautogui import time # 安全设置:快速移动到左上角(0,0)可触发异常停止程序 pyautogui.FAILSAFE = True # 获取屏幕尺寸 screen_width, screen_height = pyautogui.size() print(f"屏幕尺寸: {screen_width}x{screen_height}") # 移动鼠标到指定位置 (例如屏幕中心) target_x = screen_width // 2 target_y = screen_height // 2 pyautogui.moveTo(target_x, target_y, duration=1) # 1秒内移动到位 # 执行鼠标点击 (左键单击) pyautogui.click() # 默认左键单击 print("已在屏幕中心完成左键单击") # 示例:在坐标(100,200)处右键双击 pyautogui.click(x=100, y=200, button='right', clicks=2, interval=0.25) print("在(100,200)完成右键双击") # 示例:特定区域连续点击 for i in range(3): pyautogui.click(300, 400 + i*50) # 垂直向下点击三次 time.sleep(0.5) # 每次点击间隔0.5秒 ``` ### 代码详解 1. **安装依赖**: ```bash pip install pyautogui ``` 2. **核心功能**: - `moveTo(x,y)`:移动鼠标到指定坐标 - `click()`:执行鼠标点击,支持参数: - `x`, `y`:目标坐标(可选) - `button`:`left`(默认)/`right`/`middle` - `clicks`:点击次数(默认1) - `interval`:多次点击的时间间隔 - `size()`:获取屏幕分辨率 3. **安全机制**: - 设置 `FAILSAFE = True`(默认启用)后,快速将鼠标移动到屏幕左上角(0,0)可立即终止程序 - 建议在操作前添加 `time.sleep(5)` 留出中断时间 ### 高级应用 ```python # 获取当前鼠标位置 current_x, current_y = pyautogui.position() print(f"当前位置: ({current_x}, {current_y})") # 相对移动 (基于当前位置) pyautogui.moveRel(50, -100, duration=0.5) # 右移50px,上移100px # 拖动操作 (按住拖动) pyautogui.dragTo(500, 300, duration=1) # 拖动到(500,300) # 滚动操作 pyautogui.scroll(10) # 向上滚动10个单位 pyautogui.scroll(-20) # 向下滚动20个单位 ``` ### 注意事项 1. 多显示器系统需注意坐标系统(主显示器为(0,0)起始) 2. 游戏/全屏应用可能需要管理员权限 3. 使用 `pyautogui.PAUSE = 0.5` 可设置所有操作后的暂停时间
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值