WH_GETMESSAGE的全局挂钩仅挂钩到一个应用程序(VisualStudio)

时间:2019-07-16 07:52:26

标签: c# c++ hook setwindowshookex

我有一个C#应用程序,该应用程序为挂钩过程调用了一个外部DLL文件。 挂接过程只需“劫持”按键,即可将小写字符转换为大写字符。我认为这样做只是为了发现只有VisualStudio被成功钩住了。 chromeexplorer之类的其他应用程序似乎没有执行挂接过程。创建全局挂钩有什么我想念的?

非常感谢您的帮助。

dllmain.cpp文件:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"

#include <stdio.h>
#include <ctime>

#pragma data_seg("Shared")
HHOOK hkKey = NULL;
HINSTANCE hInstHookDll = NULL;  //our global variable to store the instance of our DLL
#pragma data_seg() //end of our data segment

#pragma comment(linker,"/section:Shared,rws")    

__declspec(dllexport) LRESULT CALLBACK procCharMsg(int nCode, WPARAM wParam, LPARAM lParam)
//this is the hook procedure
{       
    MSG* msg;
    char charCode;
    if (nCode >= 0 && nCode == HC_ACTION)

    {           
        msg = (MSG*)lParam;
        if (msg->message == WM_CHAR)                
        {
            charCode = msg->wParam;
            if (IsCharLower(charCode))
                //we check if the character pressed is a small letter
            {
                //if so, make it to capital letter
                charCode -= 32;
                msg->wParam = (WPARAM)charCode;
                //overwrite the msg structure's wparam 
                //with our new value. 
            }
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
    //passing this message to target application
}

extern "C" __declspec(dllexport) void __stdcall SetHook()
 {
     if (hkKey == NULL)
         hkKey = SetWindowsHookEx(WH_GETMESSAGE, procCharMsg, hInstHookDll, 0); // initialize global hook
 }

 //remove the hook
extern "C" __declspec(dllexport) void __stdcall RemoveHook()
 {
     if (hkKey != NULL)
         UnhookWindowsHookEx(hkKey);
     hkKey = NULL;
 }

 INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved) {
     switch (Reason)
     {
     case DLL_PROCESS_ATTACH:
         //we initialize our variable with the value that is passed to us
         hInstHookDll = (HINSTANCE)hDLL;             
         break;
     case DLL_PROCESS_DETACH:
         RemoveHook();
         break;
     default:
         break;          
     }    

     return TRUE;    
 }

从dll文件调用钩子的主要应用功能:

IntPtr hInstance = IntPtr.Zero;
IntPtr hProc = IntPtr.Zero;    
private delegate void HookSetting();

public void SetHook()
        {
            hInstance = LoadLibrary("Dll1");

            if (IntPtr.Zero == hInstance)
            {
                // null check
            }
            hProc = GetProcAddress(hInstance, "_SetHook@0");
            if(IntPtr.Zero == hProc)
            {
                // null check
            }
            HookSetting hookset = (HookSetting)Marshal.GetDelegateForFunctionPointer(hProc, typeof(HookSetting));
            hookset();                
        }

0 个答案:

没有答案