Hook及其应用(续)
KeyBoard Hook的范例
Hook Function的三个参数
nCode wParam lParam 传回值
HC_ACTION或HC_NOREMOVE 表按键Virtual Key 与WM_KEYDOWN同 若信息要被处理传0 反之传1
Public hHook as Long Public Sub UnHookKBD() If hnexthookproc <> 0 Then UnhookWindowsHookEx hHook hHook = 0 End If End Sub Public Function EnableKBDHook() If hHook <> 0 Then Exit Function hhook = SetWindowsHookEx(WH_KEYBOARD, AddressOf MyKBHFunc, App.hInstance, App.ThreadId) End Function Public Function MyKBHFunc(ByVal iCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long MyKBHfunc = 0 '表示要处理这个信息 If wParam = vbKeySnapshot Then '侦测 有没有按到PrintScreen键 MyKBHFunc = 1 '在这个Hook便吃掉这个信息 End If Call CallNextHookEx(hHook, iCode, wParam, lParam) '传给下一个Hook End Function
上面说了这么多,我们来看一个具体的应用示例,那就是——如何拦截键盘输入!这个程序使用Keyboard Hook 的范例。
以下是模块程序.Bas
Option Explicit Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal ncode As Long, ByVal wParam As Long, lParam As Any) As Long Public hnexthookproc As Long Public Const HC_ACTION = 0 Public Const WH_KEYBOARD = 2 Public Sub UnHookKBD() If hnexthookproc <> 0 Then UnhookWindowsHookEx hnexthookproc hnexthookproc = 0 End If End Sub Public Function EnableKBDHook() If hnexthookproc <> 0 Then Exit Function End If hnexthookproc = SetWindowsHookEx(WH_KEYBOARD, AddressOf _ MyKBHFunc, App.hInstance, 0) If hnexthookproc <> 0 Then EnableKBDHook = hnexthookproc End If End Function Public Function MyKBHFunc(ByVal iCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long '这三个参数是固定的,不能动,而MyKBHFunc这个名称只要和 'SetWindowsHookex()中 AddressOf後的名称一样便可,不一定叫什麽 'wParam 是传入按了哪个key的virtual-key code '如果您将以下的两行unmark则所有键盘的输入皆没有作用 'MyKBHFunc = 1 '吃掉信息 'Exit Function MyKBHFunc = 0 '信息要处理 If iCode < 0 Then MyKBHFunc = CallNextHookEx(hnexthookproc, iCode, wParam, lParam) Exit Function End If If wParam = vbKeySnapshot Then '侦测 有没有按到PrintScreen键 MyKBHFunc = 1 '在这个Hook便吃掉这个信息 Debug.Print "haha" Else Call CallNextHookEx(hnexthookproc, iCode, wParam, lParam) End If End Function '以下在Form Private Sub Form_Load() Call EnableKBDHook End Sub Private Sub Form_Unload(Cancel As Integer) Call UnHookKBD End Sub