winform 获取窗体DPI缩放比例

 

private float GetDpiScale(Form form)
{
    float num;
    using (Graphics g = form.CreateGraphics())
    {
        num = g.DpiX / 96f;
    }
    return num;
}

 

  • 在标准96DPI(100%缩放)的显示器上,此值为96

  • 在125%缩放时,通常为120

  • 在150%缩放时,通常为144

  • 在200%缩放时,通常为192

应用场景

// 示例:使控件大小适应DPI缩放
private void AdjustForDpi(Form form)
{
    float scale = GetDpiScale(form);
    
    // 根据DPI缩放调整控件
    button1.Width = (int)(button1.Width * scale);
    button1.Height = (int)(button1.Height * scale);
    
    // 或者调整字体大小
    button1.Font = new Font(button1.Font.FontFamily, 
                           button1.Font.Size * scale);
}

改进建议

虽然这个方法能工作,但在现代.NET应用程序中,有更好的替代方案:

使用Control.DpiScale属性(.NET Framework 4.7+)

private float GetDpiScaleBetter(Form form)
{
    // 更简单且可靠的方法
    return form.DeviceDpi / 96f;
}

 

posted @ 2026-01-16 10:42  家煜宝宝  阅读(2)  评论(0)    收藏  举报