VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
首页 - 经验之谈 - 如何过滤键盘录入
发表评论(0)作者:, 平台:, 阅读:10626, 日期:2000-03-12
如何过滤键盘录入

在 VB 的应用得到以前就处理键盘动作, 实现对键盘的全面控制, 可过滤任意的键。 下面的例子过滤了 CTRL+C 键, 并把该键模拟为在 Command1 上单击。

Public Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) 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 PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Const WH_KEYBOARD = 2

Public Const KBH_MASK = &H20000000

Public Const WM_LBUTTONDOWN = &H201

Public Const WM_LBUTTONUP = &H202

Global hHook As Long

'KeyboardProc 在 VB 应用动作前发生

Public Function KeyboardProc(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

If nCode >= 0 Then

'处理你希望过滤的键

If wParam = Asc("C") And (lParam And KBH_MASK) <> 0 Then

If (lParam And &HC0000000) = 0 Then

'模拟在Command1 中单击

Form1.Command1.SetFocus

Call PostMessage(Form1.Command1.hwnd, WM_LBUTTONDOWN, 0, &H20002)

Call PostMessage(Form1.Command1.hwnd, WM_LBUTTONUP, 0, &H20002)

KeyboardProc = 1

Exit Function

End If

End If

End If

KeyboardProc = CallNextHookEx(hHook, nCode, wParam, lParam)

End Function

 

Private Sub Form_Load()

'将 KeyboardProc 连接到中断上

hHook = SetWindowsHookEx(WH_KEYBOARD, AddressOf KeyboardProc, 0&, App.ThreadID)

End Sub

Private Sub Form_Unload(Cancel As Integer)

Call UnhookWindowsHookEx(hHook)

End Sub