从另一个进程调用 SetDllDirectory 不起作用?

Calling SetDllDirectory from another process doesn't work?

我一直在尝试找到一种方法来切换我不拥有的程序的 Dll 目录,来自一个 "injector" 程序,该程序应该切换 Dll 加载目录以加载修改后的或点击 Dll。

函数如下:

void AddDirectory(HANDLE Handle, const char* DllPath)
{
    void *Function, *String;
    Function = (void*)(SetDllDirectoryA);
    String = (void*)VirtualAllocEx(Handle, NULL, strlen(DllPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
    CreateRemoteThread(Handle, NULL, NULL, (LPTHREAD_START_ROUTINE)Function, (void*)String, NULL, NULL);
}

我看不出为什么这行不通?

感谢 Ben Volgt 提供的上述帮助!

编辑:请注意,正如 Ben Volgt 所说,您必须确保在加载 DLL 之前可以及时拦截进程以更改目录。因此这并不总是有效,尽管在我的情况下它确实有效。

如果有人想要拦截进程加载位置,可以在此处找到代码:

    void AddDirectory(HANDLE Handle, const char* DllPath)
{
    if (!Handle)
    {
        //Error Message or Redirect
    }

    LPVOID AddDllDirAddr = (LPVOID)GetProcAddress(GetModuleHandleA("kernel32.dll"), "SetDllDirectoryA");
    if (!AddDllDirAddr)
    {
        //Error Message or Redirect
    }

    LPVOID Alloc = VirtualAllocEx(Handle, NULL, strlen(DllPath), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!Alloc)
    {
        //Error Message or Redirect
    }

    WriteProcessMemory(Handle, Alloc, DllPath, strlen(DllPath), NULL);
    HANDLE Thread = CreateRemoteThread(Handle, NULL, NULL, (LPTHREAD_START_ROUTINE)AddDllDirAddr, Alloc, 0, NULL);
    if (!Thread)
    {
        //Error Message or Redirect
    }

    WaitForSingleObject(Thread, INFINITE);
    VirtualFreeEx(Handle, Alloc, strlen(DllPath), MEM_RELEASE);
    CloseHandle(Thread);
    CloseHandle(Handle);
}