问题
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#?
回答1:
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
回答2:
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
来源:https://stackoverflow.com/questions/6082733/how-do-i-detect-if-the-users-font-dpi-is-set-to-small-large-or-something-el