前提:64位系统需要用64位编译dll
一、首先创建一个dll工程,取名为KeyboardHookDll,代码如下:
// KeyboardHookDll.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define MYAPI extern "C" _declspec(dllexport) //导出函数声明
HHOOK hHook = NULL;
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
LRESULT lResult;
//(lParam & 0x80000000)为0时表示按下,为1时表示抬起,PS:如果修改为“抬起”则在控制台不输出字母a
if(wParam == 'A' && !(lParam & 0x80000000)) { //这里的字母必须是大写的A
lResult=CallNextHookEx(hHook, nCode, wParam, lParam);
MessageBox(hwnd, L"你按下了A", L"A", MB_OK);
return lResult;
}
return 1;
}
MYAPI int SetHook()
{
hHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, GetModuleHandleA("KeyboardHookDll.dll"), 0);
if (hHook == NULL)
{
printf("SetWindowsHookEx() error :%d
", GetLastError());
return -1;
}
return 0;
}
MYAPI int StopHook()
{
if (UnhookWindowsHookEx(hHook) == FALSE)
{
printf("UnhookWindowsHookEx() error :%d
");
return -1;
}
return 0;
}
二、新建一个控制台程序,用来启用HOOK,代码如下:
#include "stdafx.h"
#include "windows.h"
#include <iostream>
#pragma comment(lib,"KeyboardHookDll.lib")
using namespace std;
extern "C" _declspec(dllimport) void SetHook();
extern "C" _declspec(dllimport) void StopHook();
int _tmain(int argc, _TCHAR* argv[])
{
char YesNo;
printf("这是一个关于全局键盘钩子的测试...
");
printf("安装全局键盘钩子...
");
SetHook();
printf("是否卸载键盘钩子: (Y or N)
"); //当然了,下面的语句根本无法执行
YesNo = getchar();
if (YesNo == 'Y' || YesNo == 'y')
{
printf("开始卸载钩子...
");
StopHook();
printf("钩子已经卸载...
");
}
system("pause");
return 0;
}