使用全局挂钩的前提是使用DLL
DLL.cpp
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
HMODULE thisModule;
HHOOK hook;
LRESULT CALLBACK LaunchListener(int nCode, WPARAM wParam, LPARAM lParam);
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
thisModule = hModule;
// Very restricted set of things that can be done in DllMain, refer to documentation
// before adding anything here.
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#ifdef __cplusplus // If used by C++ code,
extern "C" { // we need to export the C interface
#endif
__declspec(dllexport) HHOOK AttachHook(DWORD threadID) {
hook = SetWindowsHookEx(WH_CALLWNDPROC, LaunchListener, thisModule, threadID);
return hook;
}
#ifdef __cplusplus
}
#endif
LRESULT CALLBACK LaunchListener(int nCode, WPARAM wParam, LPARAM lParam) {
// process event here
if (nCode >= 0) {
CWPSTRUCT* cwp = (CWPSTRUCT*)lParam;
if (cwp->message == WM_ACTIVATE) {
if (LOWORD(cwp->wParam) == WA_INACTIVE)
{
//the window being deactivated
MessageBox(NULL, TEXT("deactivated"), NULL, MB_OK);
}
else
{
//the window being activated
MessageBox(NULL, TEXT("activated"), NULL, MB_OK);
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
Test_Hook.cpp
#include <Windows.h>
#include <stdio.h>
//LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return DefWindowProc(hwnd, message, wParam, lParam);
};
HINSTANCE hinst;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevinstance, PSTR szCmdLine, int iCmdShow) {
HWND hwnd;
hinst = GetModuleHandle(NULL);
// create a window class:
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hinst;
wc.lpszClassName = "hooking";
// register class with operating system:
RegisterClass(&wc);
// create and show window:
hwnd = CreateWindow("hooking", "hooking", WS_OVERLAPPEDWINDOW, 0, 0, 500, 400, NULL, NULL, hinst, NULL);
if (hwnd == NULL) {
return 0;
}
ShowWindow(hwnd, SW_SHOW);
DWORD threadID = GetWindowThreadProcessId(hwnd, NULL);
HINSTANCE hinstDLL = LoadLibrary(TEXT("..\\Debug\\ProcHookDLL.dll"));
HHOOK(*AttachHookProc)(DWORD);
AttachHookProc = (HHOOK(*)(DWORD)) GetProcAddress(hinstDLL, "AttachHook");
// AttachHookProc(threadID);
HHOOK HOOK = AttachHookProc(threadID);
int i = GetLastError();
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
需要注意的是,这个仅限于检测当前窗口的活动状态,等我有时间再测试能否检测其他窗口的状态。