[英]Get Mouse Wheel Scroll usin Win32api in Python
我想讀取鼠標滾輪滾動事件,然后模擬它們。 我知道我可以使用下面的代碼來模擬它。
#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 獲取滾動事件的方法。 有沒有辦法檢測滾輪向上或向下滾動事件?
如果您需要獲取全局WM_MOUSEWHEEL
消息,可以使用SetWindowsHookEx
function 和WH_MOUSE_LL
掛鈎。
然后處理鈎子 function 中的WM_MOUSEWHEEL
消息。
這是一個示例:
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)
這個對我有用:
編輯
如果出現<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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.