5

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?

zooropa
  • 3,929
  • 8
  • 39
  • 61

2 Answers2

6

You could use GetCurrentProcessId to get the current process Id.

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

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.

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

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • I'm going to try to create a small window like you and shf301 suggested. – zooropa Jan 22 '11 at 02:53
  • creating windows is of course very possible BUT it really should'nt be your first choice - windows are somewhat resource hungry, have their own needs and are generally targeted towards actual UI application with their own message loops (be it implicitly or explictly), thats a lot to consider and implement for a small DLL. Its usually much better to either pass an HWND reference to the DLL via DLL functions or grab some verifiable HWND from a running, controllable process - this process has to be monitored, of course ... – specializt Jul 02 '15 at 12:08
  • 1
    @specializt Don't always agree, though - if you're not certain how your DLL will be used, and want it to be general purpose, it's a safe option. Relying on an HWND that could get destroyed has its own drawbacks. – Reed Copsey Jul 02 '15 at 18:08
  • generating windows inside of DLLs is _never_ "safe". At all. Its actually a security risk and stability issue since your DLL can be unloaded / destroyed without being notified, leaking whole windows and so on. Its what professionals call "bad code", mostly. If this were still 1990's such a DLL could easily crash the whole system because its being overloaded with memory leaks. Thank god its the 21s century. – specializt Jul 03 '15 at 09:10
1

Call GetGUIThreadInfo on 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).

MSalters
  • 173,980
  • 10
  • 155
  • 350