windows 如何检测用户的字体 (DPI) 是否设置为小、大或其他?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6082733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:53:38  来源:igfitidea点击:

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

.netwindowsvb.netwinformsdpi

提问by Didier Levy

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

我需要确定用户的屏幕是否设置为普通 96 dpi(小尺寸)、120 dpi 大字体或其他字体。我如何在 VB.NET(首选)或 C# 中做到这一点?

回答by Cody Gray

The bestway 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 AutoScaleModepropertyto AutoScaleMode.Dpiand enable the AutoSizeproperty. You can do this either from the Properties Window in the designer or though code:

最好的只是让表格的方式自动调整自身的大小,根据用户当前的DPI设置。要做到这一点,只需将AutoScaleMode属性设置为AutoScaleMode.Dpi并启用该AutoSize属性。您可以从设计器中的“属性”窗口或通过代码执行此操作:

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 Paintevent handler method), you can extract the information from the DpiXand DpiYproperties of the Graphicsclassinstance.

或者,如果您在绘制时需要知道这些信息(例如在Paint事件处理程序方法中),您可以从实例的DpiXDpiY属性中提取信息。Graphics

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 Graphicsclass for your form, and check the DpiXand DpiYproperties, as shown above. The CreateGraphicsmethodof the form class makes this very easy to do; just ensure that you wrap the creation of this object in a Usingstatementto avoid memory leaks. Sample code:

最后,如果您需要即时确定 DPI 级别,则必须Graphics为您的表单创建该类的临时实例,并检查DpiXDpiY属性,如上所示。表单类的CreateGraphics方法使这很容易做到;只需确保将此对象的创建包装在Using语句中以避免内存泄漏。示例代码:

Dim dpiX As Single
Dim dpiY As Single

Using g As Graphics = myForm.CreateGraphics()
    dpiX = g.DpiX
    dpiY = g.DpiY
End Using

回答by keyboardP

Have a look at the DpiXand DpiYproperties. For example:

查看DpiXDpiY属性。例如:

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

In VB:

在VB中:

Using gfx As Graphics = form.CreateGraphics()
    userDPI = CInt(gfx.DpiX)
End Using