.NET Core C# WinForms如何修改应用程序标题栏颜色
修改WinForms窗体标题栏颜色的方法
WinForms默认没有直接修改标题栏颜色的属性,你可以通过以下两种方式实现:
方法一:使用DWM API保留系统标题栏交互
这个方法适用于想保留系统默认的最小化、最大化、关闭按钮,仅修改标题栏背景色的场景,支持Windows 10 1809及以上版本。
- 在窗体代码中引入DWM API声明:
using System.Runtime.InteropServices; [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); private const int DWMWA_CAPTION_COLOR = 35;
- 在窗体加载时调用API设置颜色:
protected override void OnLoad(EventArgs e) { base.OnLoad(e); // 替换为你想要的颜色,这里示例为红色 int targetColor = Color.FromArgb(255, 0, 0).ToArgb(); DwmSetWindowAttribute(this.Handle, DWMWA_CAPTION_COLOR, ref targetColor, sizeof(int)); }
方法二:隐藏默认标题栏,自定义绘制
如果需要完全自定义标题栏样式(包括按钮、文本),可以隐藏系统标题栏后自行绘制:
设置窗体基础属性:
- 将
FormBorderStyle设为None - 开启
DoubleBuffered属性以减少绘制闪烁 - 设置
Padding.Top为30(自定义标题栏的高度,可按需调整)
- 将
绘制标题栏背景与文本:
protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // 绘制标题栏背景 using (SolidBrush bgBrush = new SolidBrush(Color.FromArgb(255, 0, 0))) { e.Graphics.FillRectangle(bgBrush, 0, 0, this.Width, 30); } // 绘制窗体标题文本 using (Font titleFont = new Font("Segoe UI", 10, FontStyle.Regular)) { e.Graphics.DrawString(this.Text, titleFont, Brushes.White, new Point(10, 8)); } }
- 添加窗口拖动功能:
protected override void WndProc(ref Message m) { const int WM_NCHITTEST = 0x0084; const int HTCLIENT = 0x01; const int HTCAPTION = 0x02; base.WndProc(ref m); if (m.Msg == WM_NCHITTEST && (int)m.Result == HTCLIENT) { // 让客户区响应拖动标题栏的操作 m.Result = (IntPtr)HTCAPTION; } }
- 自定义窗口控制按钮:
添加三个Button控件放在标题栏右侧,分别绑定事件实现最小化、最大化/还原、关闭功能:
// 最小化按钮点击事件 private void btnMinimize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } // 最大化/还原按钮点击事件 private void btnMaximize_Click(object sender, EventArgs e) { this.WindowState = this.WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized; } // 关闭按钮点击事件 private void btnClose_Click(object sender, EventArgs e) { this.Close(); }
内容的提问来源于stack exchange,提问作者Muhammad Hussnain Fareed
相关产品推荐
相关产品推荐

