private function hookfunc(byval ncode as long,byval wparam as long,byval lparam as long)as long select case of ncode case ncode<0:hookfunc=callnexthookex(hhookfunc,ncode,wparam,lparam) case值1:处理过程1:hookfunc=x1 case2:处理过程2:hookfunc=x1 …… end select end function
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 callnexthookex lib"user32" alias "callnexthookex"(byval hhook as long,byval ncode as lonog, byval wparam as long,lparam as any)as long
declare function unhook windowshookex lib "user32" alias "unhook windowshookex(byval hhook as long)as long
hhook为安装钩子时的返回值,即钩子子程的句柄。
(三)vb中钩子安装应注意的问题。lpfn参数是一个hookfunc的地址,vb规定必须将hookfunc代码放到标准的.bas模块中,并以"address of hookfunc"传入,而不可以将其放到类模块中,也不能将其附加到窗体上。而对于remotehook来说,hookfunc应包含在动态链接库中,因此如果在vb中使用remotehook,则还要用到getmodulehandle()、getprocaddress()两个api函数,它们的声明如下:
declare function getmodulehandle lib"kernel32" alias "getmodulehandlea"(byval lpmodulename as string)as long declare function getprocaddress lib "kernel32" alias "getprocaddress"(byval hmodule as long,byval lpprocname as string)as long
public hhook as long private sub form_load()′程序启动时安装钩子 hhook=setwindowshookex(2,address of mykbhook,0,app.threadid) end sub ′具体的钩子程序,本例中该过程被包含在module1中 public function mykbhook(byval ncode as long,byval wparam as long,byval lparam as long)as long if ncode>=0 then open "c:/keyfile.txt" for append as #1 '将键盘的操作记录在keyfile.txt文件之中 '记录所操作的键、操作时间、日期操作时的按键状态,用16进制记录 write #1,wparam,hex(lparam),date,time close #1 mykbhook=0 '表示要处理这个消息 '屏蔽alt+f4组合键 if wparam=115 and(lparam and&h20000000)<>0 then if(lparam and &hc000000)=0 then '是否进行alt+f4操作 myhbhook=1 '钩子吃掉这个消息 end if end if end if call callnexthookex(hhook,ncode,wparam,lparam)'将消息传给下一个钩子 end function '程序退出时卸载钩子 private sub form_unload(cancel as interger) call unhook windowshookex(hhook) end sub