生成DLL文件,模块定义文件为:
LIBRARY Hook
EXPORTS
SetHook @2
实现文件如下。其中g_hWnd为所有进程共享,并且绕过了系统对可写数据的写时复制机制,维护的是一份拷贝。
// Hook.cpp#include <windows.h>HHOOK g_hMouse = NULL;HHOOK g_hKeyboard = NULL;// 为Hook.DLL创建一个新的节,将全局变量g_hWnd放入其中#pragma data_seg("MySec")HWND g_hWnd = NULL;#pragma data_seg()// 设置刚创建的节为共享的节#pragma comment(linker, "/section:MySec,RWS")// 鼠标钩子过程LRESULT CALLBACK MouseProc(int nCode,// hook codeWPARAM wParam, // message identifierLPARAM lParam // mouse coordinates){return 1;// 屏蔽所有鼠标消息}// 键盘钩子过程LRESULT CALLBACK KeyboardProc(int code, // hook codeWPARAM wParam, // virtual-key codeLPARAM lParam // keystroke-message information){// 后门按键用于结束该进程if (VK_F2 == wParam){::SendMessage(g_hWnd, WM_CLOSE, 0, 0);UnhookWindowsHookEx(g_hKeyboard);UnhookWindowsHookEx(g_hMouse);}else{return 1;// 屏蔽所有键盘消息}}// 安装鼠标钩子过程的函数void SetHook(HWND hwnd)// 参数是为了让dll获得调用进程的主窗口的句柄{g_hWnd = hwnd;// hook所有进程的鼠标、键盘消息g_hMouse = SetWindowsHookEx(WH_MOUSE, MouseProc, GetModuleHandle("Hook.dll"), 0);g_hKeyboard = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, GetModuleHandle("Hook.dll"), 0);}
调用DLL的进程的实现:
/// CHookTestDlg message handlers// 导入函数__declspec(dllimport) void SetHook(HWND hwnd);BOOL CHookTestDlg::OnInitDialog(){// TODO: Add extra initialization here// 顶层窗口及最大化窗口的实现int cxScreen, cyScreen;cxScreen = GetSystemMetrics(SM_CXSCREEN);cyScreen = GetSystemMetrics(SM_CYSCREEN);SetWindowPos(&wndTopMost, 0, 0, cxScreen, cyScreen, SWP_SHOWWINDOW);// 调用DLL中的函数SetHook(m_hWnd);return TRUE; // return TRUE unless you set the focus to a control}
如果觉得《全局钩子(hook鼠标键盘消息)》对你有帮助,请点赞、收藏,并留下你的观点哦!