Search code examples
c++winapidll-injection

SetWindowsHookEx DLL unloading


I am using SetWindowsHookEx to inject a dll into another process. However, when the injector program exits, the dll is unloaded from the other process. Is there anyway for me to stop the unloading ? Basically, I want the dll to persist permanently regardless of whether the injector program is still running. If I am able to increase the dll reference count from within the dll, that could work. But I haven't found a way.


Solution

  • exist 2 way 1.) most effective - use LdrAddRefDll - this do exactly what you need in shortest way. you need use ntdll.lib (or ntdllp.lib) for linking.

    LdrAddRefDll(0, (HMODULE)&__ImageBase);
    

    2)not nice and effective but work

    WCHAR sz[MAX_PATH];
    if (GetModuleFileName((HMODULE)&__ImageBase, sz, RTL_NUMBER_OF(sz)))
    {
        LoadLibrary(sz);
    }