How do I get the handle of the primary monitor?

Raymond Chen

The primary monitor by definition has its upper left corner at (0, 0). Therefore, you can use this function:

HMONITOR GetPrimaryMonitorHandle()
{
 const POINT ptZero = { 0, 0 };
 return MonitorFromPoint(ptZero, MONITOR_DEFAULTTOPRIMARY);
}

To make double extra sure (belt and suspenders), we also tell it, “If you’re not sure what monitor to return, give us the primary.”

Sure, this sounds obviously simple, but I actually found somebody who fumbled around in the dark passing intentionally invalid parameters to MonitorFromWindow trying to find one that would return the primary monitor handle. (I’ve heard this called Programming By Accident.)

0 comments

Discussion is closed.

Feedback usabilla icon