Freigeben über


How To Get The Display's Color Depth using NetCF Version 1

I've seen this asked about recently on the NetCF (microsoft.public.dotnet.framework.compactframework) newsgroup, and it fits nicely with yesterday's display related p/invoke, too... :)

You may have noticed that, in version 1 of the .NET Compact Framework, the Screen object (System.Windows.Forms.Screen) does not specify the color depth of the display device (Bounds, PrimaryScreen, WorkingArea are provided).  The color depth may be useful, if you are writing an application to working with graphics, you may wish to limit a user's color palette based on what the display is capable of showing, for example.

Fortunately, getting this information is not difficult.  You only need two p/invoke calls: GetDC() and GetDeviceCaps().

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class DisplayInfo
{
    public static void Main()
    {
        // get the dimensions of the display
        Rectangle screen = Screen.PrimaryScreen.Bounds;

        // get the color depth (bits per pixel)
        //  first, we get the handle to the primary display (using GetDC)
        IntPtr deviceHandle = GetDC(IntPtr.Zero);
        if(IntPtr.Zero == deviceHandle)
        {
            // our call to GetDC failed
            MessageBox.Show("Failed to get device handle");
            return;
        }
       
        // if we get here, we can query the device capabilities
        Int32 colorDepth = GetDeviceCaps(deviceHandle, BitsPerPixel);       

        // release the device context
        //  0 == not released
        //  1 == released
        if(0 == ReleaseDC(IntPtr.Zero, deviceHandle))
        {
            MessageBox.Show("Failed to release the device handle");
        }
       
        // build a string containing the information we will show
        String msg = String.Format("{0} x {1} {2} bpp",
                                screen.Width,
                                screen.Height,
                                colorDepth);
       
        // display the screen info
        MessageBox.Show(msg, "Screen information");
    }

    // GetDeviceCaps index value(s)
    private const Int32 BitsPerPixel = 12;

    // pinvoke methods
    [DllImport("coredll.dll", SetLastError=true)]
    private extern static IntPtr GetDC(IntPtr hwnd);
   
    [DllImport("coredll.dll", SetLastError=true)]
    private extern static Int32 ReleaseDC(IntPtr hwnd,
                                        IntPtr hdc);

    [DllImport("coredll.dll", SetLastError=true)]
    private extern static Int32 GetDeviceCaps(IntPtr hdc,
                                            Int32 index);
}

Enjoy!
-- DK

[Edit: Add call to ReleaseDC]

Disclaimer(s):
This posting is provided "AS IS" with no warranties, and confers no rights.

Comments