VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - 何拦截键盘输入
发表评论(0)作者:不详, 平台:VB6.0+Win98, 阅读:11698, 日期:2001-09-28
何拦截键盘输入


作者: cww 

  这是使用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