I need Mouse hook in userform:
Private Sub UserForm_Initialize()
SetHookInOtherInstance
End Sub
Private Sub UserForm_Terminate()
RemoveHookInOtherInstance
End Sub
and it work fine in the same instance, but I want to use another to prevent Excel from crashing while debugging etc (that's the best idea from this question ) and just nothing happens.
Private Declare PtrSafe Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As LongPtr) As LongPtr
Private Declare PtrSafe Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As LongPtr, ByVal lpFn As LongPtr, ByVal hmod As LongPtr, ByVal dwThreadId As LongPtr) As LongPtr
Private Declare PtrSafe Function CallNextHookEx Lib "user32" (ByVal hHook As LongPtr, ByVal nCode As LongPtr, ByVal wParam As LongPtr, lParam As Any) As LongPtr
Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" () As LongPtr
Private i As Long
Private HookHandle As LongPtr
Private ExcelOtherInstance As Excel.Application
Private Const WH_MOUSE = 7
Private Const HC_ACTION = 0
Public Sub SetHookInOtherInstance()
Set ExcelOtherInstance = New Excel.Application
ExcelOtherInstance.Visible = True
ExcelOtherInstance.Workbooks.Add
ExcelOtherInstance.Workbooks.Open ThisWorkbook.FullName, False, True
ExcelOtherInstance.Run "SetHook", GetCurrentThreadId
End Sub
Public Sub RemoveHookInOtherInstance()
On Error Resume Next
ExcelOtherInstance.Run "RemoveHook"
End Sub
Public Sub RemoveHook()
On Error Resume Next
UnhookWindowsHookEx HookHandle
End Sub
Public Sub SetHook(ThreadId As LongPtr)
HookHandle = SetWindowsHookEx(WH_MOUSE, AddressOf NewProc, 0, ThreadId)
End Sub
Public Function NewProc(ByVal lngCode As LongPtr, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr
If lngCode = HC_ACTION Then
Application.StatusBar = CStr(i)
i = i + 1
End If
NewProc = CallNextHookEx(HookHandle, lngCode, wParam, lParam)
Exit Function
End Function
Any ideas?