API 挂钩 Windows

问题描述 投票:0回答:1

我使用 WH_CBT 钩子类型的 SetWindowsHookEx 编写了一个程序,以便在每次调整 gui 窗口大小时进行拦截,并将字符串“resized”写入 txt 文件中。 但问题是,当我执行程序时,会写入一个“字符串”条目,然后当我调整其他窗口的大小时,不会写入任何条目。 我给你提供了程序和dll: 节目:

#include <Windows.h>

int main()
{
    HMODULE hDll = LoadLibrary(TEXT("C:\\Users\\user\\Desktop\\Dll1.dll"));
    if (hDll == NULL)
    {
        // Failed to load DLL, handle error
        return 1;
    }

    auto hook = (HOOKPROC)GetProcAddress(hDll, "HookProc");
    if (hook == NULL)
    {
        // Failed to get function address, handle error
        FreeLibrary(hDll);
        return 1;
    }

    // Install the hook
    HHOOK hHook = SetWindowsHookEx(WH_CBT, hook, hDll, 0);
    if (hHook == NULL)
    {
        // Failed to install the hook, handle error
        FreeLibrary(hDll);
        return 1;
    }

    // Run the message loop

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Uninstall the hook when finished
    UnhookWindowsHookEx(hHook);

    // Free the DLL
    FreeLibrary(hDll);

    return 0;
}

DLL:

#include "pch.h"
#include <windows.h>


extern "C" __declspec(dllexport) LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    HHOOK hHOOK;
    if (nCode == WM_SIZE) {
        // Open file for writing
        HANDLE hFile = CreateFile(L"C:\\Users\\user\\Desktop\\text.txt", GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, 0, nullptr);
     

        // Write "a" to file
        char buffer[] = "resized";
        DWORD dwBytesWritten;
        WriteFile(hFile, buffer, sizeof(buffer), &dwBytesWritten, NULL);

        // Close file handle
        CloseHandle(hFile);
    }

    
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:

        break;
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

提前谢谢您。

我期望每次调整窗口大小时都会写入字符串“resized”的新条目

windows winapi hook
1个回答
0
投票

我很确定您在写入之前必须先查找到文件末尾。我相当确定 CreateFile 不会自动将您置于最后。使用 SetFilePointer。

© www.soinside.com 2019 - 2024. All rights reserved.