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

.NET Core C# WinForms如何修改应用程序标题栏颜色

修改WinForms窗体标题栏颜色的方法

WinForms默认没有直接修改标题栏颜色的属性,你可以通过以下两种方式实现:

方法一:使用DWM API保留系统标题栏交互

这个方法适用于想保留系统默认的最小化、最大化、关闭按钮,仅修改标题栏背景色的场景,支持Windows 10 1809及以上版本。

  1. 在窗体代码中引入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;
  1. 在窗体加载时调用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));
}

方法二:隐藏默认标题栏,自定义绘制

如果需要完全自定义标题栏样式(包括按钮、文本),可以隐藏系统标题栏后自行绘制:

  1. 设置窗体基础属性:

    • 将FormBorderStyle设为None
    • 开启DoubleBuffered属性以减少绘制闪烁
    • 设置Padding.Top为30(自定义标题栏的高度,可按需调整)
  2. 绘制标题栏背景与文本:

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));
    }
}
  1. 添加窗口拖动功能:
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;
    }
}
  1. 自定义窗口控制按钮:
    添加三个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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:22:35