I'm a C++ beginner (3-4 month) and I'm trying to do lean about windows hooking. I had a bug with a DLL that I'm trying to inject and after a while I realized that my DllMain is not being called! I looked at almost every thread on StackOverflow and can't figure out my problem. I found that out by intializing a variable to 5, changing it to 1 in DllMain and I output the variable in a function. The variable never change. Here is the code:
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;
}
And here is my loading the 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;
}
The output:
INSTALLING HOOK...
5 // We can see here that the DLL never changed the value of i to 1.
SUCCESS
UNINSTALL HOOK...
HINSTANCE
, notHANDLE
, but as they're bothtypedef void *
I don't think that could be causing your problem. Is DllMain being exported? - Harry Johnston