gpt4 book ai didi

python - 在 Python 中使用 Win32api 获取鼠标滚轮滚动

转载 作者:行者123 更新时间:2023-12-04 15:11:46 30 4
gpt4 key购买 nike

我想读取鼠标滚轮滚动事件,然后模拟它们。我知道我可以使用以下代码模拟它。

#Scroll one up
win32api.mouse_event(MOUSEEVENTF_WHEEL, x, y, 1, 0)

#Scroll one down
win32api.mouse_event(MOUSEEVENTF_WHEEL, x, y, -1, 0)

但是,我找不到在 Python 中使用 win32api 获取 whell 滚动事件的方法。有什么方法可以检测滚轮向上或向下滚动事件吗?

最佳答案

如果需要获取全局WM_MOUSEWHEEL消息,您可以使用 SetWindowsHookEx 功能和 WH_MOUSE_LL钩子(Hook)。

然后处理WM_MOUSEWHEEL钩子(Hook)函数中的消息。

这是一个示例:

import win32api 
import win32con
import ctypes
from ctypes import windll, CFUNCTYPE, POINTER, c_int, c_void_p, byref

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

def LowLevelMouseProc(nCode, wParam, lParam):
if wParam == win32con.WM_MOUSEWHEEL:
print("mousewheel triggerd!")
return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam)

if __name__ == '__main__':
CMPFUNC = CFUNCTYPE(c_void_p, c_int, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)

pointer = CMPFUNC(LowLevelMouseProc)
hook_id = user32.SetWindowsHookExW(win32con.WH_MOUSE_LL,pointer,c_void_p(win32api.GetModuleHandle(None), 0)
msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
user32.TranslateMessage(msg)
user32.DispatchMessageW(msg)

对我有用:

enter image description here

编辑

如果出现类似<class'OverflowError'>: int too long to convert的问题,你可以试试下面的代码:

import win32api 
import win32con
import ctypes
from ctypes import windll, CFUNCTYPE, c_int, c_void_p, wintypes



user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
user32.CallNextHookEx.argtypes = [ctypes.wintypes.HHOOK,c_int, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM]



def LowLevelMouseProc(nCode, wParam, lParam):
if wParam == win32con.WM_MOUSEWHEEL:
print("mousewheel triggerd!")
return user32.CallNextHookEx(hook_id, nCode, wParam, lParam)



if __name__ == '__main__':
CMPFUNC = CFUNCTYPE(c_void_p, c_int, ctypes.wintypes.WPARAM, ctypes.wintypes.LPARAM)
user32.SetWindowsHookExW.argtypes = [c_int,CMPFUNC,ctypes.wintypes.HINSTANCE,ctypes.wintypes.DWORD]
pointer = CMPFUNC(LowLevelMouseProc)
hook_id = user32.SetWindowsHookExW(win32con.WH_MOUSE_LL,pointer,win32api.GetModuleHandle(None), 0)
msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
user32.TranslateMessage(msg)
user32.DispatchMessageW(msg)

关于python - 在 Python 中使用 Win32api 获取鼠标滚轮滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65098845/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com