windows 如何获取 DLL 加载进程句柄

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3365190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:55:34  来源:igfitidea点击:

How to get a DLL loading process handle

c++windowswinapidllcode-injection

提问by pigiuz

I'm trying to get the handle to the process which loaded a dll from the dll.

我正在尝试获取从 dll 加载 dll 的进程的句柄。

My approach is: in DLL_PROCESS_ATTACH I call EnumWindows(EnumWindowsProc,NULL);

我的方法是:在 DLL_PROCESS_ATTACH 中我调用 EnumWindows(EnumWindowsProc,NULL);

my EnumWindowsProc implementation is the following:

我的 EnumWindowsProc 实现如下:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    if(GetCurrentProcessId() == GetWindowThreadProcessId(hWnd,NULL)){
        MessageBox(hWnd,L"I loaded your dll!",L"it's me",MB_OK);
        return TRUE;
}
    return FALSE;
}

the problem is that GetCurrentProcessId() == GetWindowThreadProcessId(hWnd,NULL) is never true (if i place the messagebox call outside the if block everything works but it gets called once for every listed window).

问题是 GetCurrentProcessId() == GetWindowThreadProcessId(hWnd,NULL) 永远不会为真(如果我将消息框调用放在 if 块之外,一切正常,但它会为每个列出的窗口调用一次)。

Is there any other way to get to the point? Is this approach totally wrong or am I just missing something?

有没有其他方法可以达到目的?这种方法是完全错误的还是我只是遗漏了什么?

Thanx in advance

提前谢谢

回答by Aaron Klotz

Use GetCurrentProcess, which returns a pseudo-handle to the current process. If you need a real handle, pass in the pseudo-handle to DuplicateHandle.

使用GetCurrentProcess,它向当前进程返回一个伪句柄。如果您需要真正的句柄,请将伪句柄传递给DuplicateHandle

Note that it is very dangerous to do too much in DllMain. Calling anything other than KERNEL32functions is quite dangerous, and even then there are some KERNEL32functions that you shouldn't be calling. See the DllMaindocumentation, this document, and severalblogpostsfromMicrosoft developers recommending against doing too much in DllMain.

请注意,在DllMain. 调用KERNEL32函数以外的任何东西都是非常危险的,即使那样,也有一些KERNEL32函数是你不应该调用的。查看DllMain文档,这个文档,以及几个博客帖子微软的开发人员建议反对这样做的太多DllMain

回答by monoceres

Easiest way would be to simply use GetCurrentProcesswhenever you need the handle.

最简单的方法是在需要句柄时简单地使用GetCurrentProcess

回答by ntcolonel

回答by Martin Rosenau

You made a mistake:

你犯了一个错误:

GetWindowThreadProcessId does not return the process ID but the thread ID.

GetWindowThreadProcessId 不返回进程 ID,而是返回线程 ID。

Your program must be written like this:

你的程序必须这样写:

BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
    DWORD process;
    GetWindowThreadProcessId(hWnd,&process);
    if(GetCurrentProcessId() == process){
        MessageBox(hWnd,L"I loaded your dll!",L"it's me",MB_OK);
        return TRUE;
    }
    return FALSE;
}