SetWindowsHookEx中使用的回调函数只调用一次

时间:2014-03-28 16:46:35

标签: c++ dll-injection setwindowshookex

我正在编写一个注入dll的全局键盘钩子,但遇到了一个我似乎无法解决的问题。到目前为止,我有一个程序负责加载dll并调用SetWindowsHookEx,并且当然要注入dll。

DLL看起来像这样:

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <string>

using namespace std;

INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved) {
    switch(Reason) {
    case DLL_PROCESS_ATTACH:
                //fprintf(file, "DLL attach function called.\n");
        break;
    case DLL_PROCESS_DETACH:
                //fprintf(file, "DLL detach function called.\n");
        break;
    case DLL_THREAD_ATTACH:
                //fprintf(file, "DLL thread attach function called.\n");
        break;
    case DLL_THREAD_DETACH:
                //fprintf(file, "DLL thread detach function called.\n");
        break;
    }

    return TRUE;
}

extern "C" __declspec(dllexport) int meconnect(int code, WPARAM wParam, LPARAM lParam) {

    if (code == HC_ACTION)
    {
        FILE *file;
        string c;
        c += (char)wParam;
        fopen_s(&file, "c:\\temp2.txt", "a+");
        fprintf(file, c.c_str());
        fclose(file);
    }
    return(CallNextHookEx(NULL, code, wParam, lParam));
}

主程序如下:

#include <Windows.h>
#include <iostream>
#include <SDKDDKVer.h>

using namespace std;

void CheckForExit(HHOOK handle);

int main()
{

    /*
    * Load library in which we'll be hooking our functions.
    */
    HMODULE dll = LoadLibrary(L"dllinject.dll");
    if (dll == NULL) {
        printf("The DLL could not be found.n");
        //getchar();
        return -1;
    }

    /*
    * Get the address of the function inside the DLL.
    */
    HOOKPROC addr = (HOOKPROC)GetProcAddress(dll, "meconnect");
    if (addr == NULL) {
        printf("The function was not found.n");
        //getchar();
        return -1;
    }

    DWORD id = GetCurrentThreadId();
    HHOOK handle = SetWindowsHookEx(WH_KEYBOARD, addr, dll, 0);

    if (handle == NULL) {
        printf("The KEYBOARD could not be hooked.n");
    }

    /*
    * Unhook the function.
    */
    system("pause");
    UnhookWindowsHookEx(handle);
    return 0;
}

0 个答案:

没有答案