CallbackOnCollectedDelegate was detected
Message: A callback was made on a garbage collected delegate of type 'MyApplication!MyApplication.Mouse+LowLevelMouseHookProc::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
Somebody have any idea what is causing this error above? Thanks in advance.
Here' the code;
Imports System.ComponentModel
Public Class Mouse
Inherits Component
Private hMouseHook As IntPtr = IntPtr.Zero
Private disposedValue As Boolean = False
Public Event LeftMouseButtonDown As MouseEventHandler
Public Event LeftMouseButtonUp As MouseEventHandler
Public Event MouseMove As MouseEventHandler
Private Structure API_POINT
Public x As Integer
Public y As Integer
End Structure
Private Structure MSLLHOOKSTRUCT
Public pt As API_POINT
Public mouseData As Integer
Public flags As Integer
Public time As Integer
Public dwExtraInfo As IntPtr
End Structure
Private Const WM_LBUTTONDOWN As Integer = &H201
Private Const WM_LBUTTONUP As Integer = &H202
Private Const WH_MOUSE_LL As Integer = 14
Private Declare Auto Function LoadLibrary Lib "kernel32" _
(ByVal lpFileName As String) As IntPtr
Private Declare Auto Function SetWindowsHookEx Lib "user32.dll" _
(ByVal idHook As Integer, ByVal lpfn As LowLevelMouseHookProc, _
ByVal hInstance As IntPtr, ByVal dwThreadId As Integer) As IntPtr
Private Declare Function CallNextHookEx Lib "user32" _
(ByVal hhk As IntPtr, ByVal nCode As Integer, ByVal wParam As Integer, _
ByRef lParam As MSLLHOOKSTRUCT) As Integer
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hhk As IntPtr) As Boolean
Private Delegate Function LowLevelMouseHookProc(ByVal nCode As Integer, _
ByVal wParam As Integer, _
ByRef lParam As MSLLHOOKSTRUCT) As Integer
Private Sub HookMouse()
Dim hInstance As IntPtr = LoadLibrary("User32")
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, AddressOf Me.HookProc, hInstance, 0)
End Sub
Private Sub UnhookMouse()
UnhookWindowsHookEx(hMouseHook)
End Sub
Private Function HookProc(ByVal nCode As Integer, ByVal wParam As Integer, _
ByRef lParam As MSLLHOOKSTRUCT) As Integer
Try
If nCode >= 0 Then
Select Case wParam
Case WM_LBUTTONDOWN
RaiseEvent LeftMouseButtonDown(Me, New MouseEventArgs _
(MouseButtons.Left, 0, lParam.pt.x, lParam.pt.y, 0))
Case WM_LBUTTONUP
RaiseEvent LeftMouseButtonUp(Me, New MouseEventArgs _
(MouseButtons.Left, 0, lParam.pt.x, lParam.pt.y, 0))
Case Else
Console.WriteLine(wParam)
End Select
End If
Return CallNextHookEx(hMouseHook, nCode, wParam, lParam)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Function
Private Function mouseHooked() As Boolean
Return hMouseHook <> IntPtr.Zero
End Function
Public Sub hookInput()
HookMouse()
End Sub
Public Sub unhookInput()
UnhookMouse()
End Sub
End Class