October 13th, 2010

How do I get the color depth of the screen?

How do I get the color depth of the screen? This question already makes an assumption that isn’t always true, but we’ll answer the question first, then discuss why the answer is wrong.

If you have a device context for the screen, you can query the color depth with a simple arithmetic calculation:

colorDepth = GetDeviceCaps(hdc, BITSPIXEL) *
             GetDeviceCaps(hdc, PLANES);

Now that you have the answer, I’ll explain why it’s wrong, but you can probably guess the reason already.

Two words: Multiple monitors.

If you have multiple monitors connected to your system, each one can be running at a different color depth. For example, your primary monitor might be running at 32 bits per pixel, while the secondary is stuck at 16 bits per pixel. When there was only one monitor, there was such a thing as the color depth of the screen, but when there’s more than one, you first have to answer the question, “Which screen?”

To get the color depth of each monitor, you can take your device context and ask the window manager to chop the device context into pieces, each corresponding to a different monitor.

EnumDisplayMonitors(hdc, NULL, MonitorEnumProc, 0);
// this function is called once for each "piece"
BOOL CALLBACK MonitorEnumProc(HMONITOR hmon, HDC hdc,
                              LPRECT prc, LPARAM lParam)
{
   // compute the color depth of monitor "hmon"
   int colorDepth = GetDeviceCaps(hdc, BITSPIXEL) *
                    GetDeviceCaps(hdc, PLANES);
   return TRUE;
}

If you decide to forego splitting the DC into pieces and just ask for “the” color depth, you’ll get the color depth information for the primary monitor.

As a bonus (and possible optimization), there is a system metric GetSystemMetrics(SM_SAMEDISPLAYFORMAT) which has a nonzero value if all the monitors in the system have the same color format.

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.