79194270

Date: 2024-11-16 00:07:20
Score: 0.5
Natty:
Report link

In short, your code is full of Undefined Behavior.
Check [SO]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer) for a common pitfall when working with CTypes (calling functions). That's the cause.

Your error (126) is also triggered by that. Check the @TODO line in my code (below).

I'm posting a corrected variant.

code00.py:

#!/usr/bin/env python

import ctypes as cts
import msvcrt
import sys
from ctypes import wintypes as wts

import win32api as wapi
import win32con as wcon


WH_MOUSE = 7
WH_MOUSE_LL = 14

LRESULT = cts.c_size_t

HOOKProc = cts.WINFUNCTYPE(LRESULT, cts.c_int, wts.WPARAM, wts.LPARAM)
LowLevelMouseProc = HOOKProc
MouseProc = HOOKProc

kernel32 = cts.windll.kernel32
user32 = cts.windll.user32

SetWindowsHookExA = user32.SetWindowsHookExA
SetWindowsHookExA.argtypes = (cts.c_int, HOOKProc, wts.HINSTANCE, wts.DWORD)
SetWindowsHookExA.restype = wts.HHOOK

CallNextHookEx = user32.CallNextHookEx
CallNextHookEx.argtypes = (wts.HHOOK, cts.c_int, wts.WPARAM, wts.LPARAM)
CallNextHookEx.restype = LRESULT

UnhookWindowsHookEx = user32.UnhookWindowsHookEx
UnhookWindowsHookEx.argtypes = (wts.HHOOK,)
UnhookWindowsHookEx = wts.BOOL

GetLastError = kernel32.GetLastError
GetLastError.argtypes = ()
GetLastError.restype = wts.DWORD

GetModuleHandleW = kernel32.GetModuleHandleW
GetModuleHandleW.argtypes = (wts.LPCWSTR,)
GetModuleHandleW.restype = wts.HMODULE  # @TODO - cfati: Decomment to run into your error

GetCurrentThreadId = kernel32.GetCurrentThreadId
GetCurrentThreadId.argtypes = ()
GetCurrentThreadId.restype = wts.DWORD


def handle_mouse_event(code, w_param, l_param):
    #print("kkt")
    if code < 0:
        return CallNextHookEx(code, w_param, l_param)
    else:
        if w_param == wcon.WM_LBUTTONDOWN:
            print("LB down")
        elif w_param == wcon.WM_LBUTTONUP:
            print("LB up")
        return CallNextHookEx(code, w_param, l_param)


low_level_mouse_proc = LowLevelMouseProc(handle_mouse_event)


def main(*argv):
    k = b"\x00"
    while k != b"\x1B":
        print("Press a key (ESC to continue) ...")
        k = msvcrt.getch()
    print("Add hook:")
    hinstance = GetModuleHandleW(None)
    tid = 0 #GetCurrentThreadId()
    print(hinstance, tid)
    hook = SetWindowsHookExA(
        WH_MOUSE_LL,
        low_level_mouse_proc,
        hinstance,
        tid,
    )
    print(f"Hook function: {hook}")
    if not hook:
        print(f"Hook creation failed: {GetLastError()}")
        return -1
    k = b"\x00"
    while k != b"\x1B":
        print("Press a key (ESC to continue) ...")
        k = msvcrt.getch()
    UnhookWindowsHookEx(hook)


if __name__ == "__main__":
    print(
        "Python {:s} {:03d}bit on {:s}\n".format(
            " ".join(elem.strip() for elem in sys.version.split("\n")),
            64 if sys.maxsize > 0x100000000 else 32,
            sys.platform,
        )
    )
    rc = main(*sys.argv[1:])
    print("\nDone.\n")
    sys.exit(rc)

Not posting the output, as there's nothing relevant. Note that after setting the hook:

Might be related:

Reasons:
  • Blacklisted phrase (1): How do I
  • Probably link only (1):
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @TODO
  • High reputation (-2):
Posted by: CristiFati