I'm using setWindowHookEx and it works fine:
Private HookHandle As LongPtr
Sub RemoveHook()
UnhookWindowsHookEx HookHandle
End Sub
Sub SetHook()
Dim lThreadID As LongPtr
lThreadID = GetCurrentThreadId
HookHandle = SetWindowsHookEx(WH_MOUSE, AddressOf foo, 0, lThreadID)
End Sub
Public Function foo(ByVal nCode As LongPtr, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr
foo = CallNextHookEx(0, nCode , wParam, lParam)
End Function
My problem is: When any unhandled errors (from any other macro) occures, and I have to end macro, Excel crashes and dies. (I'm guessing, that hook is still alive, but foo function is no longer in memory)
Is there any way to prevent Excel crash?
I use it from many modules, and I don't want make error handling everywhere.