2010年7月19日 星期一

全域鍵盤欄截 Keyboard Hook (Block Key)

原出處
Imports System.Runtime.InteropServices

Public Class Form1

Private Sub Form1_Load(ByVal s As Object, ByVal e As EventArgs) Handles MyBase.Load
KbHook.BlockKey = Keys.F1 ' 阻斷 F1 按鈕
KbHook.StartHook() ' 開始 Hook
End Sub

Private Sub Form1_FormClosing(ByVal s As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
KbHook.StopHook() ' 停止 Hook
End Sub

End Class

Public Class KbHook ' Keyboard Hook Class

' 宣告 API
Private Delegate Function HookProc _
(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

Private Declare Auto Function SetWindowsHookEx Lib "user32.dll" _
(ByVal idHook As Integer, ByVal lpfn As HookProc, _
ByVal hMod As IntPtr, ByVal dwThreadId As Integer) As IntPtr

Private Declare Function UnhookWindowsHookEx Lib "user32.dll" (ByVal hhk As IntPtr) As Boolean

Private Declare Function CallNextHookEx Lib "user32.dll" _
(ByVal hhk As IntPtr, ByVal nCode As Integer, _
ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr

Shared hk As IntPtr
Public Shared BlockKey As Keys = 0

Public Shared Function KbProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
If Marshal.ReadInt32(lParam) = BlockKey Then Return True
Return CallNextHookEx(hk, nCode, wParam, lParam)
End Function

Public Shared Sub StartHook()
hk = SetWindowsHookEx(13, AddressOf KbProc, Marshal.GetHINSTANCE(GetType(KbHook).Module), 0)
End Sub

Public Shared Sub StopHook()
UnhookWindowsHookEx(hk)
End Sub

End Class

沒有留言:

張貼留言