C++钩子,HOOK编程,全局钩子


全局钩子,HOOK编程,

建立DLL项目:

代码如下:

#include"pch.h"
#define _DLL_API
#include"MyDLL.h"

HHOOK MouseHook = NULL;
HHOOK KeyBoargHook = NULL;

HINSTANCE g_hinst;            //获取主模块的句柄,

//创建一个节,只要是包含在节内的数据,多进程是共享的,节内的数据必须初始化,dumpbin /headers 查看dll信息
#pragma data_seg("MySec")
HWND g_hwnd = NULL;
#pragma data_seg()

#pragma comment(linker,"/section:MySec,RWS")        //使用linker连接方式,设置MySec读写共享权限

//鼠标钩子
LRESULT __stdcall MouseProc(int nCode, WPARAM wparam, LPARAM lparam)
{
    return 1;
}

//键盘钩子
LRESULT __stdcall KeyBoardHook(int nCode, WPARAM wparam, LPARAM lparam)
{
    if (wparam == VK_F2)                            //当按下F2时退出
    {
        ::SendMessage(g_hwnd, WM_CLOSE, 0, 0);
        UnhookWindowsHookEx(KeyBoargHook);
    }
    return 1;
}

//接口
void SetMouseHook(HWND hwnd)                            
{
    g_hwnd = hwnd;
    MouseHook = SetWindowsHookExW(WH_MOUSE, MouseProc, g_hinst, 0);
}
//接口

void SetKeyBoardHook(HWND hwnd)                        //为了给主窗口发消息,我们定义了一个窗口句柄参数。
{
    g_hwnd = hwnd;
    KeyBoargHook = SetWindowsHookEx(WH_KEYBOARD, KeyBoardHook, g_hinst, 0);
}

DLLMAIN:

#include "pch.h"

extern HINSTANCE g_hinst;

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{
    g_hinst = hModule;
    
    return TRUE;
}

  通过头文件导出,也可以def导出。

#pragma once

#ifndef MYDLL_H
#define MYDLL_H

#ifdef _DLL_API
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)

#endif // DLL_API

DLL_API void SetMouseHook(HWND hwnd);

DLL_API void SetKeyBoardHook(HWND hwnd);


#endif

生成dll项目,拿到dll和lib

在其他的窗口项目中,调用这两个接口,便会出现全局效果。

OK!

相关