Search code examples
winapigdi

Availability of handles presented in MONITORENUMPROC callback of EnumDisplayMonitors


The MONITORENUMPROC callback function of EnumDisplayMonitors gives me two handles. One of the type HMONITOR and one HDC.

  • HMONITOR should reference the monitor.
  • HDC is the handle to the device context of that monitor.

Do I need to release any of those handles before returning from the callback function? If not, how long will they stay around? May I save them for later use?


Solution

  • Do I need to release any of those handles before returning from the callback function?

    No, unless it is explicitly stated in the document to release, like the GetWindowDC function: After painting is complete, the ReleaseDC function must be called to release the device context.

    May I save them for later use?

    Generally speaking, yes. A physical display has the same HMONITOR as long as it is part of the desktop. When a WM_DISPLAYCHANGE message is sent, any monitor may be removed from the desktop and thus its HMONITOR becomes invalid or has its settings changed. Therefore, an application should check whether all HMONITOR are valid when this message is sent.

    HDC handle is from the EnumDisplayMonitors, and its life cycle depends on the HDC parameter in EnumDisplayMonitors.