屏蔽键盘的键(如 Win、Ctrl),使用底层键盘钩子(Hook)

'从网上找来的,原文……大家不要费脑筋去读了,因为把它整理成 VB 懂的格式费了我20分钟。
'可以屏蔽一切你想要屏蔽的键……当然代码要输入完全,否则……

'模块代码(mMain.bas)

Option Explicit

Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
Private 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
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)

Private Type PKBDLLHOOKSTRUCT
    vkCode As Long
    scanCode As Long
    flags As Long
    time As Long
    dwExtraInfo As Long
End Type

Private Const WM_KEYDOWN = &H100
Private Const WM_SYSKEYDOWN = &H104
Private Const WM_KEYUP = &H101
Private Const WM_SYSKEYUP = &H105
Private Const VK_LWIN = &H5B
Private Const VK_RWIN = &H5C
Private Const HC_ACTION = 0
Private Const WH_KEYBOARD_LL = 13
Private Const VK_CONTROL = &H11
Private Const VK_ESCAPE = &H1B
Private Const VK_MENU = &H12
Private Const VK_TAB = &H9
Private Const VK_Delete = &H2E

Private lngHook As Long

'使用底层KeyboardHook阻拦按键消息
Public Function LowLevelKeyboardProc(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim blnHook As Boolean
    Dim p As PKBDLLHOOKSTRUCT
    If nCode = HC_ACTION Then
        Select Case wParam
        Case WM_KEYDOWN, WM_SYSKEYDOWN, WM_KEYUP, WM_SYSKEYUP
            Call CopyMemory(p,ByVal lParam,Len(p))
            If p.vkCode = VK_LWIN Or p.vkCode = VK_RWIN Then blnHook = True '按下了左/右Win键
            If p.vkCode = VK_CONTROL Or p.vkCode = VK_ESCAPE Then blnHook = True '按下了Ctrl Esc键,如不需屏蔽可注释这句
            If p.vkCode = VK_MENU Or p.vkCode = VK_TAB Then blnHook = True '按下了Alt Tab键,如不需屏蔽可注释这句
        Case Else '不做
        End Select
    End If
    If blnHook Then
        LowLevelKeyboardProc = 1
    Else
        Call CallNextHookEx(WH_KEYBOARD_LL,nCode,wParam,lParam)
    End If
End Function

Public Sub HooK()
    lngHook=SetWindowsHookEx(WH_KEYBOARD_LL, AddressOf LowLevelKeyboardProc, App.hInstance, 0)
End Sub

Public Sub UnHooK()
    Call UnhookWindowsHookEx(lngHook)
End Sub

'窗体代码(fMain.frm)

Private Sub Form_Load()
    Call HooK '屏蔽Win键
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Call UnHooK '取消屏蔽Win键
End Sub
分享到 评论