0

How can I get global scroll events with win32api on Python? I searched how can I do that and found answer: https://stackoverflow.com/a/65101276/8705882, and it is not working due to an error.

Traceback (most recent call last):
  File "H:/programing/p_python/woweyscroll/study1.py", line 21, in <module>
    hook_id = user32.SetWindowsHookExW(
ctypes.ArgumentError: argument 3: <class 'OverflowError'>: int too long to convert

If there is how to solve this error or another method of getting global mouse scroll event, please let me know!

Sch
  • 3
  • 2

1 Answers1

1

If you are running on a 64-bit system, using the win32api.GetModuleHandle(None) parameter will cause this error.

The reason is that the function recognizes the parameter as C int, you can modify it to c_void_p(win32api.GetModuleHandle(None) to solve this problem.

hook_id = user32.SetWindowsHookExW(win32con.WH_MOUSE_LL,pointer,c_void_p(win32api.GetModuleHandle(None)), 0)

This can work normally under both 32-bit and 64-bit systems.

Edit

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)
Zeus
  • 3,703
  • 3
  • 7
  • 20
  • Hi,if this answer did help to you, please feel free to mark it to help people with the same issue, and let me know if you have any problem.Thanks. – Zeus Dec 25 '20 at 08:11
  • This does not solve the problem for me. The relevant part of the stack trace: `return windll.user32.CallNextHookEx(hook_id, nCode, wParam, lParam) ctypes.ArgumentError: argument 4: : int too long to convert`. – ack Jan 14 '21 at 19:07
  • @Alex Quilliam Maybe you can use `wintypes`, I have edited my answer and you can refer to it. – Zeus Jan 15 '21 at 01:22
  • After importing `wintypes`, the new code works, thanks. Perhaps you should update your answer to the other question as well? – ack Jan 15 '21 at 02:10
  • @AlexQuilliam Yes, I have modified it, thank you for your reminder. – Zeus Jan 15 '21 at 02:12