首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VB >

VB键盘HOOK示例有关问题出在哪

2012-02-29 
VB键盘HOOK示例问题出在哪?参考文章:http://www.bitscn.com/pdb/dotnet/200605/24608.html我测试的是第一

VB键盘HOOK示例问题出在哪?
参考文章:http://www.bitscn.com/pdb/dotnet/200605/24608.html
我测试的是第一步 VB源码的部分,
运行后,点击空格,程序会立即自动退出,请帮我看看问题出在哪里。源文件如下:

窗体Form1文件内容:
VERSION 5.00
Begin VB.Form Form1 
  Caption = "Form1"
  ClientHeight = 3195
  ClientLeft = 60
  ClientTop = 345
  ClientWidth = 4680
  LinkTopic = "Form1"
  ScaleHeight = 3195
  ScaleWidth = 4680
  StartUpPosition = 3 '窗口缺省
  Begin VB.TextBox Text1 
  Height = 1545
  Left = 840
  TabIndex = 0
  Text = "Text1"
  Top = 900
  Width = 2595
  End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
'先来看一下在vb中是如何实现的。截的是空格键。表现的目标是:
'一个form,上面有一个textbox,不管焦点是否落在textbox里,按空格键,
'不会在textbox中输入一个空格,而是变成在textbox中写入一句话:“HOOK成功!”

Private Sub Form_Load()
Call EnableKBDHook
End Sub

Private Sub Form_Unload(Cancel As Integer)
 Call UnHookKBD
End Sub

模块文件内容:
Attribute VB_Name = "Module1"
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, ByVal lParam As Any) As Long

  Public hnextHookproc As Long

  Public Const WH_KEYBOARD = 2 '这个是表明Hook的种类是键盘Hook

  Public Const PM_KEY_SPACE = &H20 '空格键

  Public Sub UnHookKBD() '解键盘HOOK函数

  If hnextHookproc <> 0 Then

  UnHookWindowsHookEx (hnextHookproc)

  hnextHookproc = 0

  End If

  End Sub


  Public Function EnableKBDHook() '设置键盘HOOK

  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 = 0
  If iCode < 0 Then
  MyKBHFunc = CallNextHookEx(hnextHookproc, iCode, wParam, lParam)
  Exit Function
  End If

  If wParam = PM_KEY_SPACE Then ''偵測 有沒有按到空格鍵
  MyKBHFunc = 1
  Form1.TextBox1.Text = "Hook成功!"
  End If
  End Function



[解决办法]
Form1.TextBox1.Text = "Hook成功!"

==>

Form1.Text1.Text = "Hook成功!"

另外调试状态不能直接调试键盘HOOK的.VB6 IDE会直接退出的.

需要看是否钩子已经OK,直接Build成exe去查看.

另外
[解决办法]
楼主不妨直接参考这精华帖中的代码吧:
http://topic.csdn.net/u/20100326/16/4c8c75d3-e34c-4909-8f46-87c34cdde313.html
100 分,几分钟帮写一个小程序,谢谢。 [推荐] [基础类]

热点排行