Windows的钩子机制详解

  #include "stdafx.h"

  #include

  #include "spyhook.h"

  ……//省略部分机器生成代码

  #pragma data_seg("PublicData") //定义全局数据段

  HHOOK hhook=NULL; //钩子句柄

  HINSTANCE pInstance=NULL; //钩子模块句柄

  UINT MouseClick=0; //记录鼠标单击次数的变量

  #pragma data_seg()

  ……//省略部分机器生成代码

  extern "C" int APIENTRY

  DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)

  { if (dwReason == DLL_PROCESS_ATTACH)

  { ……//省略部分机器生成代码

  new CDynLinkLibrary(SpyDLL);

  pInstance=hInstance; //取得模块句柄

  }

  else if (dwReason == DLL_PROCESS_DETACH)

  { TRACE0("SPY.DLL Terminating!

  ");

  AfxTermExtensionModule(SpyDLL);

  }

  return 1;

  }

  extern "C" LRESULT CALLBACK MouseProc(int code,WPARAM wParam,

  LPARAM lParam) //钩子处理函数

  { if (code < 0) //若code<0,直接调用CallNextHookEx返回

  return CallNextHookEx(hhook, code, wParam, lParam);

  if(wParam==WM_LBUTTONDOWN)

  { MouseClick++; //记录鼠标单击次数

  }

  return CallNextHookEx(hhook, code, wParam,lParam);

  }

  extern "C" BOOL WINAPI StartHook() //启动钩子函数

  { hhook=SetWindowsHookEx(WH_MOUSE,MouseProc,pInstance,0); //挂上钩子

  if(hhook!=NULL)

  return TRUE;

  else return FALSE;

  }

  extern "C" BOOL WINAPI StopHook() //撤销钩子函数

  { return UnhookWindowsHookEx(hhook); //撤销钩子

  }

  extern "C" int WINAPI GetResult() //返回鼠标单击次数

  { return MouseClick;

  }