windows 如何从 DLL 中获取 HWND?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4765692/
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 16:02:36  来源:igfitidea点击:

How do I get a HWND from inside a DLL?

windowswinapidllhwnddirectsound

提问by zooropa

I have a DLL that I want to play sounds using Direct Sound. In order to play sounds, I need the HWND of the executable. I don't have a HWND of the executable that loads the DLL. How do I get that in the DLL without passing it in from the executable?

我有一个 DLL,我想使用 Direct Sound 播放声音。为了播放声音,我需要可执行文件的 HWND。我没有加载 DLL 的可执行文件的 HWND。如何在 DLL 中获取它而不从可执行文件中传递它?

回答by Reed Copsey

You could use GetCurrentProcessIdto get the current process Id.

您可以使用GetCurrentProcessId来获取当前进程 ID。

You could then call EnumWindows, and check each window with GetWindowThreadProcessIdto find a window associated with your process.

然后您可以调用 EnumWindows,并使用GetWindowThreadProcessId检查每个窗口以查找与您的进程关联的窗口。

However, an easier option might be to just generate your own Window. You can create a 1x1 pixel window that is not visible, and use it with Direct Sound.

但是,更简单的选择可能是生成您自己的窗口。您可以创建一个不可见的 1x1 像素窗口,并将其与 Direct Sound 一起使用。

This has the advantage of working even if your calling process doesn't have a usable window (or deletes window handles regularly).

即使您的调用进程没有可用的窗口(或定期删除窗口句柄),这也具有工作的优点。

回答by MSalters

Call GetGUIThreadInfoon the main thread. This gets you a bunch of HWNDs. If you need a top-level HWND, pick any valid one (not all values may be filled) and find its top level ancestor with GetAncestor(GA_ROOT).

GetGUIThreadInfo在主线程上调用。这会让你得到一堆 HWND。如果您需要顶级 HWND,请选择任何有效的(并非所有值都可以填充)并使用GetAncestor(GA_ROOT).