Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect if the user's font (DPI) is set to small, large, or something else?

I need to find out if the user's screen is set to normal 96 dpi (small size), large 120 dpi fonts, or something else. How do I do that in VB.NET (preferred) or C#?

like image 227
Didier Levy Avatar asked May 21 '11 15:05

Didier Levy


2 Answers

The best way is just to let the form resize itself automatically, based on the user's current DPI settings. To make it do that, just set the AutoScaleMode property to AutoScaleMode.Dpi and enable the AutoSize property. You can do this either from the Properties Window in the designer or though code:

Public Sub New()
    InitializeComponent()

    Me.AutoScaleMode = AutoScaleMode.Dpi
    Me.AutoSize = True
End Sub

Or, if you need to know this information while drawing (such as in the Paint event handler method), you can extract the information from the DpiX and DpiY properties of the Graphics class instance.

Private Sub myControl_Paint(ByVal sender As Object, ByVal e As PaintEventArgs)
    Dim dpiX As Single = e.Graphics.DpiX
    Dim dpiY As Single = e.Graphics.DpiY

    ' Do your drawing here
    ' ...
End Sub

Finally, if you need to determine the DPI level on-the-fly, you will have to create a temporary instance of the Graphics class for your form, and check the DpiX and DpiY properties, as shown above. The CreateGraphics method of the form class makes this very easy to do; just ensure that you wrap the creation of this object in a Using statement to avoid memory leaks. Sample code:

Dim dpiX As Single
Dim dpiY As Single

Using g As Graphics = myForm.CreateGraphics()
    dpiX = g.DpiX
    dpiY = g.DpiY
End Using
like image 59
Cody Gray Avatar answered Nov 08 '22 17:11

Cody Gray


Have a look at the DpiX and DpiY properties. For example:

using (Graphics gfx = form.CreateGraphics())
{
    userDPI = (int)gfx.DpiX;
}

In VB:

Using gfx As Graphics = form.CreateGraphics()
    userDPI = CInt(gfx.DpiX)
End Using
like image 39
keyboardP Avatar answered Nov 08 '22 18:11

keyboardP