如何在C# Windows Forms中完全禁用Windows缩放功能?
C# Windows Forms 固定像素尺寸/字体的实现方案
核心逻辑
要让应用完全不被缩放,必须明确告知Windows不要自动调整应用的像素渲染,同时禁用WinForms自身的自动缩放机制,确保所有元素严格按原始像素值显示——这正是你需要的:高DPI屏幕上物理尺寸变小,但像素数完全不变。
具体实现步骤及代码
1. 配置DPI感知(必做)
首先通过应用清单告诉Windows,应用要自己控制DPI,拒绝系统缩放:
- 在项目中添加
app.manifest文件(若没有) - 找到并修改以下代码段(取消注释并调整):
<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <!-- 系统级DPI感知:固定按100% DPI渲染 --> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware> <!-- 若需多显示器适配,改用:<dpiAware>true/PM</dpiAware>(每显示器DPI感知v2) --> </windowsSettings> </application>
2. 禁用WinForms自动缩放并固定元素
在窗体类中关闭自动缩放,固定窗口尺寸、字体及控件位置:
public partial class MainForm : Form { public MainForm() { InitializeComponent(); // 关闭WinForms自动缩放 AutoScaleMode = AutoScaleMode.None; // 固定窗口像素尺寸(示例:800×600) Size = new Size(800, 600); MaximumSize = Size; MinimumSize = Size; // 设置固定像素大小的字体(关键:用GraphicsUnit.Pixel指定单位) var fixedFont = new Font("微软雅黑", 12, FontStyle.Regular, GraphicsUnit.Pixel); Font = fixedFont; // 递归给所有子控件设置相同的固定像素字体 SetFixedFontToAllControls(Controls, fixedFont); // 手动固定控件位置(示例) button1.Location = new Point(50, 50); button1.Size = new Size(150, 40); label1.Location = new Point(50, 100); label1.Size = new Size(200, 25); } // 递归遍历所有子控件设置字体 private void SetFixedFontToAllControls(Control.ControlCollection controls, Font fixedFont) { foreach (Control ctrl in controls) { ctrl.Font = fixedFont; if (ctrl.HasChildren) SetFixedFontToAllControls(ctrl.Controls, fixedFont); } } }
3. 代码强制设置DPI感知(备选)
如果清单文件配置不生效,可在Program.cs中用代码强制开启DPI感知:
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace FixedPixelWinFormsApp { static class Program { [DllImport("user32.dll")] private static extern bool SetProcessDpiAwarenessContext(int dpiFlag); // 每显示器DPI感知v2,适合多屏场景 private const int DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -3; [STAThread] static void Main() { // 强制设置DPI感知,避免系统自动缩放 SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
效果验证
完成配置后,应用在任何DPI的屏幕上都会:
- 保持固定的像素尺寸,高DPI屏幕上物理尺寸按比例缩小
- 字体始终以指定的像素大小显示,不会被放大
- 所有控件的位置、大小严格按代码中设置的像素值呈现
内容的提问来源于stack exchange,提问作者Bambam
相关产品推荐
相关产品推荐

