Search code examples
dll-injectiondetach

DLL_PROCESS_DETACH not called C++


Sup!

i make a simple script for attaching/detaching but if i press F11, the DLL gets killed but not in the "normal way", DLL_PROCES_DETACH is not called

what can be the problem?

#include <Windows.h>
#include <thread>

HMODULE hMod            = nullptr;
bool    bDebugMode      = true;
bool    bLeave          = false;

void Setup(void);

void Setup()
{
    while (true)
    {
        if (GetAsyncKeyState(VK_F11) & 1)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
            FreeLibraryAndExitThread(hMod, 1);
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

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

        hMod = hModule;
        DisableThreadLibraryCalls(hModule);
        if(bDebugMode)
            MessageBox(NULL, "Attach", "Attached", MB_OK);

        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Setup, 0, 0, 0); break;

    case DLL_THREAD_DETACH:

        Beep(500, 100);

        if(bDebugMode)
            MessageBox(NULL, "Detach", "Detach called!", MB_OK); break;
    }
    return true;
}

any help would be appreciated!


Solution

  • Well your code is fine, except there is no case DLL_PROCESS_DETACH inside of your switch statement. Sometimes it just takes another pair of eyes to see the mistake.

    EDIT: You should be able to switch the DLL_THREAD_DETACH with DLL_PROCESS_DETACH and everything will work fine.