Search code examples
cwindowswinapigdi

What happens to an HDC when its window is destroyed?


I'm writing a library that works with HWND and HDC under the hood. ReleaseDC takes a HWND as a parameter, but what if the window has already been destroyed? Does Windows free the HDC automatically, or does this cause a resource leak?


Solution

  • When testing on Windows 10, it appears that a DC retrieved with GetDC is automatically released when the window is destroyed.

    An infinite loop that creates a window, retrieves a DC, and destroys the window had no increase of memory usage after the first iteration. To make sure some internal reference count wasn't being incremented without also being decremented, I changed the loop to repeatedly get a DC from the same window. This not only increased memory usage with each iteration, but also made my entire system slow and unstable.