本文主要解決兩個問題
- C# Winform 高 DPI 字體模糊。
- 高 DPI 下(縮放 > 100%),UI 設計工具一直提示縮放到 100%,如果不重啟到 100%,設計的控制項會亂飛。


建立測試程式
- 新增 .Net Windows 窗体應用程式 (Winform) 專案

- 選擇 .Net6.0

- 將表單尺寸設為 1000 x 1000,用於後續檢測縮放是否正確

- 加入一個按鈕,尺寸設為 150 x 50

- 加入一個圖片框,尺寸設為 300 x 300,右鍵匯入一張圖片


- 加入測試程式碼
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Text = this.Width + "x" + this.Height + " pic "+ pictureBox1.Width + "x" + pictureBox1.Height + 啟動環境();
}
public static string 啟動環境()
{
#if NET461
return (".NET Framework 4.6.1");
#elif NET6_0
return (".NET6");
#endif
}
}
}
- 執行看看效果:在 net6 下執行,尺寸都正確

正式開始
- 右鍵專案,加入應用程式資訊清單
app.manifest,檔名使用預設,修改

取消這段註解,開啟感知 DPI
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
- 雙擊專案名稱,編輯設定檔
TargetFrameworks 改為雙目標架構 <TargetFrameworks>net6.0-windows;net461;</TargetFrameworks>,儲存後提示重新載入專案,最好關閉 VS 再重新開啟一次。
完整檔案如下
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFrameworks>net6.0-windows;net461;</TargetFrameworks>
<UseWindowsForms>true</UseWindowsForms>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationVisualStyles>true</ApplicationVisualStyles>
<ApplicationUseCompatibleTextRendering>false</ApplicationUseCompatibleTextRendering>
<ApplicationHighDpiMode>SystemAware</ApplicationHighDpiMode>
</PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>
- 如果提示找不到控制項,請在 Form1.Designer.cs 和 Form1.cs 加入
using System;
using System.Windows.Forms;
Program.cs註解掉ApplicationConfiguration.Initialize();執行選擇
net461
備註:我的螢幕是 2800 x 1800,縮放 175%

果然,顯示尺寸不對

- Form1.cs 加入
AutoScaleMode = AutoScaleMode.Dpi;
public Form1()
{
AutoScaleMode = AutoScaleMode.Dpi; //加入這句,要在 'InitializeComponent();' 上方
InitializeComponent();
}
再次執行

完美!
- 雙擊編輯表單,沒有提示 100% 縮放,加入標準功能表與 DataGridView 測試

完美!雙倍的快樂!
總結
- 新增 .Net Windows 窗体應用程式 (Winform) 專案 [.Net6.0]
- 加入應用程式資訊清單
app.manifest,開啟感知 DPI TargetFrameworks改為雙目標架構<TargetFrameworks>net6.0-windows;net461;</TargetFrameworks>Program.cs註解掉ApplicationConfiguration.Initialize();AutoScaleMode = AutoScaleMode.Dpi;//加入這句,要在 'InitializeComponent();' 上方
舊專案也可以透過編輯 projet 檔案升級到這種新專案格式,支援本文說的功能,需要繼續出教學的請在評論區留言,這幾天都在度假中,今天就寫到這裡了。下次見!
對應 DEMO