August 9th, 2007

How do I get the handle of the primary monitor?

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.)

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.