钩子

1. DLL 工程包含 dll.h 和 dll.cpp 文件

 //dll.h #pragma once #define DllImport extern"C"__declspec(dllimport) DllImport void InstallHook(int nCode); DllImport LRESULT CALLBACK KeyBoardProc (int nCode,WPARAM wParam, LPARAM lParam ); DllImport void EndHook(void); //dll.cpp // dllmain.cpp : Defines the entry point for the DLL application. #include "stdafx.h" #include "LearningHook.h" #include <windows.h> #include "string.h" #include "stdio.h" HINSTANCE hInst; #pragma data_seg("hookdata") HHOOK oldkeyhook=0; #pragma data_seg() #pragma comment(linker,"/SECTION:hookdata,RWS") #define DllExport extern "C"__declspec(dllexport) DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam ); DllExport void InstallHook(int nCode); DllExport void EndHook(void); BOOL WINAPI DllMain(HINSTANCE hInstance,ULONG What,LPVOID NotUsed) { switch(What) { case DLL_PROCESS_ATTACH: hInst = hInstance; break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return 1; } void InstallHook(int nCode) { oldkeyhook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyBoardProc,hInst,0); } DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam ) { WPARAM j; FILE *fp; if(lParam&0x80000000) { j = wParam; fp=fopen("c://hook//key.txt","a"); fprintf(fp,"%4d",j); fclose(fp); } return CallNextHookEx(oldkeyhook,nCode,wParam,lParam); } void EndHook(void) { UnhookWindowsHookEx(oldkeyhook); }

 

2. 编译生成 dll.lib, dll.dll

3. 建议 win32 project "usingdll", 包含 dll.h, 加 dll.lib 为 additional dependecies. 把 dll.dll 考进 usingdll 工程目录。

4. 在 usingdll 工程中加入代码

case WM_CREATE: InstallHook(TRUE); break; case WM_DESTROY: EndHook(); PostQuitMessage(0); break;

4. 编译使用 usingdll.

你可能感兴趣的:(thread,dll,callback,keyboard,linker,winapi)