我需要找出如果用户的屏幕设置为正常的96 DPI(小尺寸),大的120 dpi的字体,或别的东西。我如何做到这一点在VB.NET(preferred)或C#?
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#?
在最佳的办法就是让形式自动调整本身,根据用户当前的DPI设置。为了使它做到这一点,只需设置AutoScaleMode物业以 AutoScaleMode.Dpi
并启用AutoSize属性。你可以做到这一点无论是从属性窗口在设计或虽然code:
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
或者,如果您需要了解这些信息,而绘图的(如在Paint事件处理方法),可以提取从DpiX和DpiY在 图形
类实例的属性。
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
最后,如果你需要确定即时的DPI级别,你必须创建图形
类的临时实例为表单,并检查在 DpiX
和 DpiY
属性,如上图所示。该CreateGraphics窗体类的方法使这很容易做到的;只是确保你包在一个 使用声明,以避免内存泄漏。样品code:
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