如何在Windows 11中编程为单个WinForm/程序禁用DWM并显示Win7风格标题栏
为单个窗体/程序禁用DWM/Aero样式(Windows 11)
针对Windows 11环境下无需兼容模式,仅通过编程实现单个窗体或整个程序禁用DWM/Aero样式的需求,以下是两种可行方案:
方案1:针对单个窗体禁用DWM非客户端渲染
使用DwmSetWindowAttribute函数(Windows 8及以上系统仍支持),可以单独为指定窗口禁用DWM的非客户端区域渲染,让窗口回退到Windows Basic样式,且不会影响全局系统的DWM状态。
C#代码示例:
首先定义P/Invoke相关的常量与函数:
using System; using System.Runtime.InteropServices; using System.Windows.Forms; public static class DwmUtils { public enum DwmWindowAttribute { DWMWA_NCRENDERING_POLICY = 2 } public enum DwmNcrenderingPolicy { DWMNCRP_USEWINDOWSTYLE, DWMNCRP_DISABLED, DWMNCRP_ENABLED, DWMNCRP_LAST } [DllImport("dwmapi.dll", PreserveSig = false)] public static extern void DwmSetWindowAttribute(IntPtr hwnd, DwmWindowAttribute attr, ref DwmNcrenderingPolicy attrValue, int attrSize); }
在窗体的加载事件中应用设置:
private void TargetForm_Load(object sender, EventArgs e) { var disablePolicy = DwmUtils.DwmNcrenderingPolicy.DWMNCRP_DISABLED; DwmUtils.DwmSetWindowAttribute(this.Handle, DwmUtils.DwmWindowAttribute.DWMWA_NCRENDERING_POLICY, ref disablePolicy, Marshal.SizeOf(disablePolicy)); this.Refresh(); }
方案2:为整个程序禁用主题渲染
如果需要让整个进程内的所有窗口都使用Windows Basic样式,可以调用SetThemeAppProperties函数,移除进程的主题支持属性。
C#代码示例:
using System.Runtime.InteropServices; public static class ThemeUtils { [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)] public static extern int SetThemeAppProperties(int props); private const int STAP_ALLOW_NONCLIENT = 0x00000001; private const int STAP_ALLOW_CONTROLS = 0x00000002; } // 在程序启动初期(如Main方法中、窗体创建前)调用 ThemeUtils.SetThemeAppProperties(0);
注意事项
- 调用
DwmSetWindowAttribute时,需确保窗体句柄已有效生成,建议在Load或Shown事件中执行。 - 部分依赖Aero样式的第三方控件,在禁用DWM后可能出现显示异常,需提前测试适配。
SetThemeAppProperties需在进程初始化阶段调用,才能对所有后续创建的窗口生效。
内容的提问来源于stack exchange,提问作者Felix An
相关产品推荐
相关产品推荐

