VB.net 2010 視頻教程 VB.net 2010 視頻教程 VB.net 2010 視頻教程
SQL Server 2008 視頻教程 c#入門經典教程 Visual Basic從門到精通視頻教程
當前位置:
魔兽世界wow > 編程開發 > vb >
  • vb教程之如何攔截鍵盤輸入

  • 2017-09-21 16:32 來源:未知
 這是使用Keyboard Hook 的范例,它的解釋請查VB5 Call WinAPI技巧或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
相關教程