You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

高分屏设备下Windows Forms DataGridView字体缩放异常求助

修复高分屏下PowerShell WinForms DataGridView字体缩放异常问题

问题根源是Windows Forms进程未正确启用高DPI感知,导致DataGridView的字体被系统重复缩放,即使和窗体使用同一个Font对象也会出现大小不一致的情况。以下是修复后的完整代码:

# 启用进程级高DPI感知
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class DpiHelper {
    [DllImport("user32.dll", SetLastError = true)]
    public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr dpiContext);
    public static readonly IntPtr DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = new IntPtr(-4);
}
"@
[DpiHelper]::SetProcessDpiAwarenessContext([DpiHelper]::DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

$Font = New-Object System.Drawing.Font("Arial",'34',[System.Drawing.FontStyle]::Regular,[System.Drawing.GraphicsUnit]::Pixel)

# 创建窗体
$form = New-Object System.Windows.Forms.Form
$form.Text = "DataGridView Example"
$form.Size = New-Object System.Drawing.Size(600, 400)
$form.Font = $Font
$form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Dpi  # 启用控件DPI自动适配

# 创建标签
$label = New-Object System.Windows.Forms.Label
$label.Text = "Example DataGridView"
$label.AutoSize = $true
$label.Location = New-Object System.Drawing.Point(20, 20)

# 创建DataGridView
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Location = New-Object System.Drawing.Point(20, 50)
$dataGridView.Size = New-Object System.Drawing.Size(560, 300)
# 同时设置单元格和列头的字体,避免单独缩放
$dataGridView.DefaultCellStyle.Font = $Font
$dataGridView.ColumnHeadersDefaultCellStyle.Font = $Font

# 创建数据表并填充数据
$table = New-Object System.Data.DataTable
$table.Columns.Add("ID", [int])
$table.Columns.Add("Name", [string])
$table.Columns.Add("Age", [int])
$table.Rows.Add(1, "John Doe", 30)
$table.Rows.Add(2, "Jane Smith", 25)
$table.Rows.Add(3, "Michael Johnson", 40)

$dataGridView.DataSource = $table

# 添加控件到窗体
$form.Controls.Add($label)
$form.Controls.Add($dataGridView)

# 显示窗体
$form.Add_Shown({$form.Activate()})
[void] $form.ShowDialog()

关键修改说明:

  • 启用高DPI感知:通过调用SetProcessDpiAwarenessContext设置进程为PER_MONITOR_DPI_AWARE_V2模式,让程序直接感知当前显示器的DPI,避免系统自动缩放。
  • 统一字体设置:不仅设置DefaultCellStyle.Font,同时设置ColumnHeadersDefaultCellStyle.Font,确保DataGridView的所有文字区域使用相同字体,避免局部缩放差异。
  • 窗体AutoScaleMode:设置为Dpi,让窗体及子控件自动根据DPI调整布局和大小。

内容的提问来源于stack exchange,提问作者Captain_Planet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 14:11:10