November 6th, 2014

How do I get a handle to the primary monitor?

There are various ways of getting a monitor. You can get the monitor from a point, from a rectangle, or from a window. But how do you get the primary monitor?

The primary monitor is defined to be the one which has (0, 0) as its origin. Therefore, one solution is

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

The desktop window by convention is deemed to reside primarily on the primary monitor, so you could also use this:

HMONITOR GetPrimaryMonitor()
{
 return MonitorFromWindow(GetDesktopWindow(),
                          MONITOR_DEFAULTTOPRIMARY);
}

Or you could just pass the null window handle. This is technically an illegal parameter, but by specifying MONITOR_DEFAULT­TO­PRIMARY, you are saying, “If anything goes wrong, give me the primary monitor.”

HMONITOR GetPrimaryMonitor()
{
 return MonitorFromWindow(nullptr,
                          MONITOR_DEFAULTTOPRIMARY);
}

In this case, we are intentionally going astray because we want to kick in the MONITOR_DEFAULT­TO­PRIMARY behavior.

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.