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

人走茶凉 提交于 2019-11-28 12:16:58

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!