写下这是为了自己复习的。
主要实现的是给File Explorer注入鼠标钩子,以检测鼠标是否在File Explorer上点击
.cpp
#include <Windows.h> #include <stdio.h> #include <psapi.h> #include <shlwapi.h> #include <tchar.h> #pragma comment(lib,"Kernel32.lib") #pragma comment(lib,"shlwapi.lib") #pragma comment(linker, "/SECTION:.shared,RWS") using namespace std; DWORD dwPID; 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 main() { Sleep(3000); //用作选择file explorer,可以用定时器代替 CHAR lpFileName[MAX_PATH] = { 0 }; HANDLE hProcess; HWND hwnd = GetForegroundWindow(); DWORD threadID = GetWindowThreadProcessId(hwnd, &dwPID); hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, dwPID); GetModuleFileNameEx(hProcess, NULL, lpFileName, _countof(lpFileName)); PathStripPath(lpFileName); if (_tcscmp(_T("explorer.exe"), lpFileName) == 0) { _tprintf(_T("explorer window found")); } else { _tprintf(_T("foreground window was not explorer window")); } CloseHandle(hProcess); HINSTANCE hinstDLL = LoadLibrary(TEXT("DLL.dll")); //这里需要新创建的dll的路径 HHOOK(*AttachHookProc)(DWORD); AttachHookProc = (HHOOK(*)(DWORD)) GetProcAddress(hinstDLL, "AttachHook"); HHOOK HOOK = AttachHookProc(threadID); int err = GetLastError();//检测是否有错误 MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } }
.dll
// 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; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: 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_MOUSE, LaunchListener, thisModule, threadID); return hook; } #ifdef __cplusplus } #endif LRESULT CALLBACK LaunchListener(int nCode, WPARAM wParam, LPARAM lParam) { // process event here if (nCode >= 0) { switch (wParam & 0x0001) { case MK_LBUTTON: { MessageBox(NULL, TEXT("Click"), NULL, MB_OK); } break; } } return CallNextHookEx(NULL, nCode, wParam, lParam); }