【问题标题】:How do I detect if the user's font (DPI) is set to small, large, or something else?如何检测用户的字体 (DPI) 是否设置为小、大或其他?
【发布时间】:2011-08-30 06:39:06
【问题描述】:

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

【问题讨论】:

  • 原生方式(用 Delphi 编写,但仅使用原生 Windows API):var dc: HDC; res: integer; begin dc := GetDC(0); if dc <> 0 then try res := GetDeviceCaps(dc, LOGPIXELSX); finally ReleaseDC(0, dc) end;
  • 正如 Andreas 建议的那样,您还可以调用 Windows API 函数 GetDCGetDeviceCaps 以获取此信息,但您必须使用 P/Invoke 从.NET 应用程序,这样做几乎没有什么好处,因为 Graphics 类已经很好地将其封装在托管代码中。
  • 但无论如何,感谢paying your taxes!!

标签: .net windows vb.net winforms dpi


【解决方案1】:

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

Public Sub New()
    InitializeComponent()

    Me.AutoScaleMode = AutoScaleMode.Dpi
    Me.AutoSize = True
End Sub

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

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 级别,则必须为您的表单创建一个 Graphics 类的临时实例,并检查 DpiXDpiY 属性,如如上所示。表单类的CreateGraphics method 让这很容易做到;只需确保将此对象的创建包装在 Using statement 中以避免内存泄漏。示例代码:

Dim dpiX As Single
Dim dpiY As Single

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

【讨论】:

  • 您好,谢谢!但是 dpi 是否与屏幕大小(X / Y)或字体大小(仅 X 可用)有关?换句话说,我可以确定在所有情况下 dpiX = dpiY 吗?否则,新字体看起来会被拉伸,不是吗?
  • @Didier:是的,通常 dpiX 将等同于 dpiY。如果没有,它看起来会很紧张。这取决于分辨率和用户选择的 DPI 设置。默认的小设置有 dpiX = 96 和 dpiY = 96。默认的大设置有 dpiX = 120 和 dpiY = 120。您可以在高 DPI 应用程序上查看this MSDN page。链接的how-to page 非常好。
【解决方案2】:

查看DpiXDpiY 属性。例如:

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

在 VB 中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2021-08-12
    • 2017-04-29
    • 2011-12-10
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多