我有一个 Windows 窗体应用程序,其中字体大小会根据整个窗口的文本大小进行更改。即使整个窗口的文本大小从小更改为中,如何在我的 Windows 窗体应用程序中保持默认字体大小?我已经将 AutoScalMode 设置为 None,但是如果它们彼此非常接近,则字体大小会与控件重叠。
谢谢
不幸的是,这是 WinForms 的一个常见问题。
如果我理解您的问题 - 当您在 WinForms 控件 fe 标签中手动设置字体时会出现问题。根据这个答案,我在下面写了代码。也许会有所帮助
获取实际 Dpi 显示尺寸:
public class FontResizeFactorProvider
{
private const int DpiSmallSize = 96;
private const int DpiMediumSize = 120;
private const int DpiLargeSize = 144;
public float GetFontResizeFactor()
{
var graphics = Graphics.FromHwnd(IntPtr.Zero);
IntPtr desktop = graphics.GetHdc();
var displayDimensions = new List<int>
{
GetDeviceCaps(desktop, (int) DeviceCap.LOGPIXELSX),
GetDeviceCaps(desktop, (int) DeviceCap.LOGPIXELSY)
};
var matchedDim = displayDimensions.First(dim => dim == DpiSmallSize || dim == DpiMediumSize || dim == DpiLargeSize);
if (matchedDim == default(int))
{
throw new ArgumentException("Dpi size not standard.");
}
var resizeFactor = (float) DpiSmallSize/matchedDim;
return resizeFactor;
}
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
public enum DeviceCap
{
/// <summary>
/// Logical pixels inch in X
/// </summary>
LOGPIXELSX = 88,
/// <summary>
/// Logical pixels inch in Y
/// </summary>
LOGPIXELSY = 90
// Other constants may be founded on pinvoke.net
}
}
负责在 Form 中调整字体大小的服务:
public class FormFontsResizeService
{
private const double EPSILON = 0.1;
private readonly FontResizeFactorProvider _fontResizeFactorProvider;
public FormFontsResizeService():this(new FontResizeFactorProvider())
{
}
public FormFontsResizeService(FontResizeFactorProvider fontResizeFactorProvider)
{
_fontResizeFactorProvider = fontResizeFactorProvider;
}
public void ResizeControlFonts(Form form)
{
var resizeFactor = _fontResizeFactorProvider.GetFontResizeFactor();
foreach (Control control in form.Controls)
{
var baseFont = control.Font;
if (Math.Abs(baseFont.Size - SystemFonts.DefaultFont.Size) < EPSILON)
{
continue;
}
var scaledFont = new Font(baseFont.FontFamily, baseFont.Size*resizeFactor, baseFont.Style);
control.Font = scaledFont;
}
}
}
表格中的用法:
protected override void OnShown(System.EventArgs e)
{
var formFontsResizeService = new FormFontsResizeService();
formFontsResizeService.ResizeControlFonts(this);
}
还要检查这个问题。