最近做画面,需要接收任何画面上的动作,于是就找些了钩子的使用代码,自己整理一下,以后也好
Imports System.Runtime.InteropServices
Public Class CKeyBoardControl
Private Shared setHookFlag As Boolean = False
Public Shared intCurrentControlIndex As Integer = 0
Private Const WH_MOUSE As Integer = 20
Private hHook As Integer = 0
Private HookProc As CallBack
Public Delegate Function CallBack(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
<DllImport("coredll", CharSet:=CharSet.Auto, CallingConvention:=3)> _
Public Overloads Shared Function GetCurrentThreadId() As Integer
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Auto, CallingConvention:=3)> _
Public Overloads Shared Function SetWindowsHookExW(ByVal idHook As Integer, ByVal HookProc As CallBack, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Auto, CallingConvention:=3)> _
Public Overloads Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
End Function
<DllImport("coredll.dll", CharSet:=CharSet.Auto, CallingConvention:=3)> _
Public Overloads Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean
End Function
Private Function SetHook() As Integer
HookProc = New CallBack(AddressOf MouseProc)
hHook = SetWindowsHookExW(WH_MOUSE, HookProc, IntPtr.Zero, GetCurrentThreadId)
Return hHook
End Function
Public Function UnHook() As Boolean
Return UnhookWindowsHookEx(hHook)
End Function
'Public Function initialControl(ByRef frmBaseForm As Form) As Integer
' CKeyBoardControl.frmBaseForm = frmBaseForm
' SetHook()
'End Function
Private Function MouseProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer
Dim contr As Control
If nCode = 0 Then
If lParam.ToInt32 > 0 Then
' Do something
'For Each contr In frmBaseForm.Controls
' If contr.Focused And _
' contr.GetType.ToString().Equals("System.Windows.Forms.UserControl") = False And _
' contr.GetType.ToString().Equals("System.Windows.Forms.Button") = False Then
' intCurrentControlIndex = contr.TabIndex
' contr.Text = intCurrentControlIndex
' Exit For
' End If
'Next
End If
End If
Return CallNextHookEx(hHook, nCode, wParam, lParam)
End Function
End Class