C#如何获取主副显示器缩放百分比?WinForms布局适配需求
获取WinForms程序所在显示器的缩放百分比
核心实现方案
方法1:获取当前窗口所在显示器的缩放比例
通过窗口的Graphics对象获取对应显示器的DPI,再基于系统默认96DPI(对应100%缩放)计算百分比:
public static float GetCurrentDisplayScale(Control control) { using (Graphics g = control.CreateGraphics()) { float scale = g.DpiX / 96f; return scale * 100; // 返回百分比值,如125、175、200等 } }
调用示例(在窗体加载时适配布局):
private void Form1_Load(object sender, EventArgs e) { float currentScale = GetCurrentDisplayScale(this); // 根据缩放比例动态调整TableLayoutPanel行高 if (currentScale >= 175) { tableLayoutPanel1.RowStyles[0].Height = 60; // 高缩放适配值 } else { tableLayoutPanel1.RowStyles[0].Height = 50; // 默认缩放值 } }
方法2:获取所有显示器的缩放比例
遍历系统所有屏幕,结合GDI API获取每个显示器的DPI并计算缩放:
public static Dictionary<Screen, float> GetAllDisplayScales() { var scaleDict = new Dictionary<Screen, float>(); foreach (Screen screen in Screen.AllScreens) { using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { IntPtr hdc = g.GetHdc(); try { int dpiX = GetDeviceCaps(hdc, 88); // LOGPIXELSX常量值为88 float scale = dpiX / 96f * 100; scaleDict.Add(screen, scale); } finally { g.ReleaseHdc(hdc); } } } return scaleDict; } // 引入GDI API声明 [System.Runtime.InteropServices.DllImport("gdi32.dll")] private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
如需获取程序所在显示器的缩放,可通过Screen.FromControl(this)在返回的字典中匹配。
关键注意事项
- 启用高DPI支持:在
Program.cs的Main方法开头添加配置,避免系统自动缩放导致布局错乱:
Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
- 监听缩放变化:当窗口拖动到其他显示器或系统缩放调整时,通过
DpiChanged事件重新适配布局:
private void Form1_DpiChanged(object sender, DpiChangedEventArgs e) { float newScale = e.DpiNew.X / 96f * 100; AdjustTableLayoutForScale(newScale); } private void AdjustTableLayoutForScale(float scale) { // 批量调整所有行的高度逻辑 foreach (RowStyle style in tableLayoutPanel1.RowStyles) { if (style.SizeType == SizeType.Absolute) { style.Height = scale >= 175 ? style.Height * 1.2f : style.Height; } } }
内容的提问来源于stack exchange,提问作者bankeris
相关产品推荐
相关产品推荐

