使用Python中的Win32api获取鼠标滚轮滚动
我想读取鼠标滚轮滚动事件,然后模拟它们。 我知道我可以用下面的代码来模拟它使用Python中的Win32api获取鼠标滚轮滚动,python,winapi,mouseevent,pywin32,mousewheel,Python,Winapi,Mouseevent,Pywin32,Mousewheel,我想读取鼠标滚轮滚动事件,然后模拟它们。 我知道我可以用下面的代码来模拟它 #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 scroll事件的方法。 是否还有检测滚轮上下滚动事件的功能?如果需要获取全局W
#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 scroll事件的方法。
是否还有检测滚轮上下滚动事件的功能?如果需要获取全局
WM\u mouseweel
消息,可以使用该功能和WH\u MOUSE\u LL
钩子
然后在hook函数中处理WM_mouseweel
消息
以下是一个示例:
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)
这对我很有用:
编辑
如果出现诸如:int太长而无法转换等问题,可以尝试以下代码:
import win32api
import win32con
import ctypes
from ctypes import windll, CFUNCTYPE, c_int, c_void_p
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)
您好,如果这个答案对您有帮助,请随时标记它以帮助有相同问题的人,如果您有任何问题,请告诉我。谢谢。