Andrew Coates ::: MSFT

It's all about community!

Finding the Windows dpi setting in .NET

Finding the Windows dpi setting in .NET

  • Comments 2

I had a note from Stephen Lead (of Ignite Spatial fame) asking how to determine the dpi setting a user has selected in Windows. He pointed me to the only MSDN article he could find on the subject, ironically explaining how to do it in Visual FoxPro. I didn’t know off the top of my head, generally you don’t have to worry about this in .NET because the framework is DPI aware and automatically scales your controls (you can control this with the ContainerControl.AutoScaleMode property). Stephen was setting the form’s height and width explicitly in code and wanted to be able to figure out what those values would be.

After some searching, I found out how to do this. All objects that inherit from System.Windows.Forms.Control inherit the CreateGraphics method which returns a System.Drawing.Graphics object for the control. The Graphics object has DpiX and DpiY properties which give respectively the resolution of the screen in dots per inch horizontally and vertically.

This means, for example, that you can grab the resolution in the form load (VB):

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   Using myGraphics As Graphics = Me.CreateGraphics()
      MessageBox.Show(String.Format("Resolution X: {0} dpi, Resolution Y: {1} dpi", myGraphics.DpiX, myGraphics.DpiY), _
                      "Windows Resolution")
   End Using
End Sub

or in C#

private void Form1_Load(object sender, EventArgs e)
{
    using (Graphics myGraphics = this.CreateGraphics())
    {
        MessageBox.Show(String.Format("Resolution X: {0} dpi, Resolution Y: {1} dpi", myGraphics.DpiX, myGraphics.DpiY),
                        "Windows Resolution");
    }
}

Either way, on my system this results in

image

Note that this works in the .NET Compact Framework as well.

Updated to include disposal of Graphics Object

Page 1 of 1 (2 items)