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

后端 未结 2 675
刺人心
刺人心 2020-12-11 04:41

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#?

相关标签:
2条回答
  • 2020-12-11 05:17

    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
    
    0 讨论(0)
  • 2020-12-11 05:20

    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
    
    0 讨论(0)
提交回复
热议问题