C# 缩放 UserControl 内容以匹配用户 Dpi/字体大小缩放、字体大小、内容、用户

2023-09-07 14:47:22 作者:陌路尘埃

如何让 OwnerDrawn UserControl 尊重用户的 dpi (96/120/xxx) 和/或字体大小(正常、大、特大)?

How do I get my OwnerDrawn UserControl to respect the users dpi (96/120/xxx) and/or font-size (normal, large, extra large)?

有些人建议在 Graphics 对象上使用 DpiX 和 DpiY 属性,但这似乎与我的控制无关(即,无论我选择哪种字体大小或 dpi,它们总是设置为 96).

Some people suggest to use the DpiX and DpiY properties on a Graphics object, but that doesn't seem to to anything in my control (i.e. they are always set to 96, regardless of which font-size or dpi I choose).

StackOverflow 上还有另一个类似的问题,它建议使用 AutoScale 属性,但建议的解决方案也没有真正做任何事情.

There is another similar question here on StackOverflow where it suggests to use the AutoScale properties, but the suggested solutions don't really do anything either.

除了依赖 WPF 之外,.NET 中没有其他办法吗?

Is there no way of doing this in .NET except for relying on WPF?

推荐答案

您需要将 UserControl 的 AutoScaleMode 属性设置为 AutoScaleMode.Dpi,不将 AutoScale 属性设置为 true.如果这样做,它会将 AutoScaleMode 重置为 None.AutoScale 属性已过时,仅用于向后兼容(请参阅此 MSDN 文章).

You would need to set the AutoScaleMode property of the UserControl to AutoScaleMode.Dpi, and not set the AutoScale property to true. If you do, it will reset the AutoScaleMode back to None. The AutoScale property is obsolete and is there only for backwards compatibility (see the Important Note in this MSDN article).

此外,在 Windows Vista/7 中,除非您明确指定您的应用程序可识别 DPI,否则 Windows 将模拟默认 DPI 环境,以便您的应用程序以 96 DPI 呈现,然后将生成的位图缩放到适当的大小.为避免这种情况,您可以更改应用程序清单以通知 Windows 您实际上可以识别 DPI - 请参阅 这篇文章.

Also, in Windows Vista/7, unless you explicitly specify that your application is DPI-aware, Windows will emulate a default DPI environment so that your application renders with 96 DPI, then scale the resulting bitmap to the appropriate size. To avoid that, you can alter your application manifest to inform Windows that you are in fact DPI aware - see the Using manifest to declare DPI awareness section in this article.