You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows系统下鼠标光标状态变化检测的Python库咨询

检测鼠标指针状态变化的Python实现方案

目前没有专门的Python库直接提供光标样式变化检测功能,但可以通过调用Windows原生API结合ctypes实现(以下方案针对Windows平台),无需额外安装第三方库:

实现思路

通过Windows API获取当前光标句柄,与系统预定义的光标句柄(如箭头、手型)对比,从而判断光标样式是否变化。核心依赖以下API:

  • GetCursorInfo: 获取当前光标信息(含句柄)
  • LoadCursor: 加载系统预定义光标,获取其句柄

代码示例

import ctypes
import time
from ctypes import wintypes

# 定义CURSORINFO结构体,用于接收光标信息
class CURSORINFO(ctypes.Structure):
    _fields_ = [
        ("cbSize", wintypes.DWORD),
        ("flags", wintypes.DWORD),
        ("hCursor", wintypes.HCURSOR),
        ("ptScreenPos", wintypes.POINT)
    ]

# 加载user32系统库
user32 = ctypes.WinDLL("user32", use_last_error=True)

# 封装API函数,指定参数和返回值类型
GetCursorInfo = user32.GetCursorInfo
GetCursorInfo.argtypes = [ctypes.POINTER(CURSORINFO)]
GetCursorInfo.restype = wintypes.BOOL

LoadCursor = user32.LoadCursorW
LoadCursor.argtypes = [wintypes.HINSTANCE, wintypes.LPCWSTR]
LoadCursor.restype = wintypes.HCURSOR

# 系统预定义光标ID
IDC_HAND = 32649    # 手型光标
IDC_ARROW = 32512   # 默认箭头光标

def get_current_cursor_handle():
    """获取当前光标句柄"""
    cursor_info = CURSORINFO()
    cursor_info.cbSize = ctypes.sizeof(CURSORINFO)
    if not GetCursorInfo(ctypes.byref(cursor_info)):
        raise ctypes.WinError(ctypes.get_last_error())
    return cursor_info.hCursor

def get_system_cursor(cursor_id):
    """获取系统预定义光标句柄"""
    return LoadCursor(None, cursor_id)

def monitor_cursor_changes():
    """持续监测光标样式变化"""
    prev_cursor_type = None
    hand_handle = get_system_cursor(IDC_HAND)
    arrow_handle = get_system_cursor(IDC_ARROW)

    print("开始监测光标变化,按Ctrl+C终止...")
    try:
        while True:
            current_handle = get_current_cursor_handle()
            current_type = None

            if current_handle == hand_handle:
                current_type = "手型(hand)"
            elif current_handle == arrow_handle:
                current_type = "箭头(arrow)"
            else:
                current_type = "自定义/其他光标"

            if current_type != prev_cursor_type:
                print(f"光标样式变更:{current_type}")
                prev_cursor_type = current_type
            time.sleep(0.1)
    except KeyboardInterrupt:
        print("\n监测结束")

if __name__ == "__main__":
    monitor_cursor_changes()

说明

  1. 适用场景:该方案对系统默认光标(箭头、手型等)的检测准确有效;如果是程序自定义的光标,无法通过系统ID匹配,需要额外对比光标图标像素(复杂度更高)。
  2. 跨平台问题:上述代码仅适用于Windows。若需Linux/Mac平台实现,需调用对应系统的图形API(如Linux用Xlib,Mac用Quartz框架),同样可通过ctypes或对应Python绑定库实现。

内容的提问来源于stack exchange,提问作者middlepost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 05:45:34