我使用WH_CBT钩子类型的SetWindowsHookEx编写了一个程序,以便在每次gui窗口调整大小时拦截并写入字符串"resize "在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;
}
提前谢谢你。
我期望每次我调整一个窗口的大小,一个新的字符串" resizing "应该写成
我很确定您在写入之前必须查找到文件的末尾。我很确定CreateFile不会自动把你放在最后。使用SetFilePointer。