Hook编程2:全局钩子

// The following ifdef block is the standard way of creating macros which make exporting 
// from a DLL simpler. All files within this DLL are compiled with the HOOK_EXPORTS
// symbol defined on the command line. this symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see 
// HOOK_API functions as being imported from a DLL, wheras this DLL sees symbols
// defined with this macro as being exported.
#ifdef HOOK_EXPORTS
#define HOOK_API __declspec(dllexport)
#else
#define HOOK_API __declspec(dllimport)
#endif

extern HHOOK g_hHook;
extern HHOOK g_hHookKey;
extern HINSTANCE g_hIns;
HOOK_API void SetHook();

  

// Hook.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "Hook.h"

HHOOK g_hHook;
HHOOK g_hHookKey;
HINSTANCE g_hIns;

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
	g_hIns =(HINSTANCE) 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;
}

LRESULT CALLBACK MouseProc(
						   int nCode,      // hook code
						   WPARAM wParam,  // message identifier
						   LPARAM lParam   // mouse coordinates
						   )
{
	return 1;
}


LRESULT CALLBACK KeyProc(
						   int nCode,      // hook code
						   WPARAM wParam,  // message identifier
						   LPARAM lParam   // mouse coordinates
						   )
{
	if(wParam == VK_F2){
		UnhookWindowsHookEx(g_hHook);
		UnhookWindowsHookEx(g_hHookKey);
		MessageBox(0,"去掉了Hook","提示",0);
		return 1;
	}
	else return CallNextHookEx(g_hHookKey,nCode,wParam,lParam);	
}

HOOK_API void SetHook()
{
	g_hHook = SetWindowsHookEx(WH_MOUSE,MouseProc,g_hIns,0);
	g_hHookKey = SetWindowsHookEx(WH_KEYBOARD,KeyProc,g_hIns,0);
}

  

原文地址:https://www.cnblogs.com/wucg/p/2429865.html