如何使用SetWindowsHookEx和WH_KEYBOARD挂钩外部进程

前端之家收集整理的这篇文章主要介绍了如何使用SetWindowsHookEx和WH_KEYBOARD挂钩外部进程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图挂钩例如记事本没有成功.制作全局钩子似乎工作正常.

在XP SP2上测试.

编辑:修改后的代码现在有效.

MyDLL代码

#include <windows.h>
#include <iostream>
#include <stdio.h>

HINSTANCE hinst;
#pragma data_seg(".shared")
HHOOK hhk;
#pragma data_seg()
//#pragma comment(linker,"/SECTION:.shared,RWS") compiler error in VC++ 2008 express

LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) {  
    if (code < 0) {
        return CallNextHookEx(0,code,wParam,lParam);
    }
    Beep(1000,20);
    return CallNextHookEx(hhk,lParam);
}

extern "C" __declspec(dllexport) void install(unsigned long threadID) { 
    hhk = SetWindowsHookEx(WH_KEYBOARD,wireKeyboardProc,hinst,threadID);
}
extern "C" __declspec(dllexport) void uninstall() {
    UnhookWindowsHookEx(hhk); 
}

BOOL WINAPI DllMain(__in HINSTANCE hinstDLL,__in  DWORD fdwReason,__in  LPVOID lpvReserved) {
    hinst = hinstDLL;
    return TRUE;
}

我的节目

#include <Windows.h>

unsigned long GetTargetThreadIdFromWindow(char *className,char *windowName)
{
    HWND targetWnd;
    HANDLE hProcess;
    unsigned long processID = 0;

    targetWnd = FindWindow(className,windowName);
    return GetWindowThreadProcessId(targetWnd,&processID);
} 

int _tmain(int argc,_TCHAR* argv[]) {
    unsigned long threadID = GetTargetProcessIdFromWindow("Notepad","Untitled - Notepad");
    printf("TID: %i",threadID);    

    HINSTANCE hinst = LoadLibrary(_T("MyDLL.dll")); 

    if (hinst) {
        typedef void (*Install)(unsigned long);
        typedef void (*Uninstall)();

        Install install = (Install) GetProcAddress(hinst,"install");
        Uninstall uninstall = (Uninstall) GetProcAddress(hinst,"uninstall");

        install(threadID);

        Sleep(20000);

        uninstall();
    }

    return 0;
}
三个问题:

您应该在使用线程ID时使用进程ID.

你的HHOOK需要进入共享内存:

#pragma data_seg(".shared")
HHOOK hhk = NULL;
#pragma data_seg()
#pragma comment(linker,RWS")

您需要将HHOOK传递给CallNextHookEx:

return CallNextHookEx( hhk,lParam);
原文链接:https://www.f2er.com/windows/364034.html

猜你在找的Windows相关文章