如何在vba中屏蔽禁用键盘按键?

有时候我们会想要禁止键盘操作,也就是无论键盘上的什么按键被按下,都不会有响应。

根据如何在vba中用钩子hook监视键盘的按键?一文,我们可以通过钩子hook屏蔽所有键盘的按键。

代码如下:

Public hHook As Long
Public 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
Public Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Public Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal ncode As Long, ByVal wParam As Long, lParam As Any) As Long
Public Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Public Declare Function GetKeyNameText Lib "user32" Alias "GetKeyNameTextA" (ByVal lParam As Long, ByVal lpBuffer As String, ByVal nSize As Long) As Long
Const WH_KEYBOARD = 2
Sub BeginHK()
    i = GetCurrentThreadId
 hHook = SetWindowsHookEx(WH_KEYBOARD, AddressOf KeyboardProc, 0, i)
End Sub
Public Function KeyboardProc(ByVal code As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    If code < 0 Then
    KeyboardProc = CallNextHookEx(hHook, code, wParam, lParam)
    Else
        '将钩子程序的返回值设置为非0,表示钩子程序处理了这个消息,不继续发送到目标窗口程序
        '就可以屏蔽所有键盘的按键
        KeyboardProc = 1
    End If
End Function
Sub EndHK()
    UnhookWindowsHookEx hHook
End Sub

 

       

仅有1条评论 发表评论

  1. iGaNg /

    如果想只屏蔽某个按键呢?

发表评论