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