我是一个 C++ 初学者(3-4 个月),我正在尝试对 windows hooking 做精益求精。我有一个我试图注入的 DLL 的错误,过了一会儿我意识到我的 DllMain 没有被调用!我几乎查看了 StackOverflow 上的每个线程,但无法弄清楚我的问题。我通过将变量初始化为 5,在 DllMain 中将其更改为 1 并在函数中输出变量来发现这一点。变量永远不会改变。这是代码:
int i = 5;
BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved )
{
i=1;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
hDll = (HINSTANCE) hModule;
break;
case DLL_THREAD_ATTACH: break;
case DLL_THREAD_DETACH: break;
case DLL_PROCESS_DETACH: break;
}
return TRUE;
}
bool InstallHook(){
cout << "INSTALLING HOOK... " << endl;
cout << i << endl;
hHook = SetWindowsHookEx(WH_CBT, (HOOKPROC) CBTProc, hDll, 0);
return hHook != NULL;
}
这是我正在加载的 DLL ......
typedef bool (*InstallHook)();
typedef void (*UninstallHook)();
InstallHook ih;
UninstallHook uh;
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
uh();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
// Bunch of code to initialize a simple window until this:
HINSTANCE hDll = LoadLibrary("e:\\projects\\DLL\\ToInject.dll");
ih = (InstallHook)GetProcAddress(hDll, "InstallHook");
uh = (UninstallHook)GetProcAddress(hDll, "UninstallHook");
if (!ih()){
cout << "SUCCESS" << endl;
}else{
cout << "FAILED" << endl;
}
// other stuff to create a window
return Msg.wParam;
}
输出:
INSTALLING HOOK...
5 // We can see here that the DLL never changed the value of i to 1.
SUCCESS
UNINSTALL HOOK...