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

如何在C# Windows Forms应用中自定义ProgressBar颜色?

在C# Windows Forms中自定义ProgressBar颜色的方法

一、基础颜色修改方法

直接通过设置ForeColor属性即可修改ProgressBar的进度颜色,步骤如下:

    1. 在窗体中添加ProgressBar控件(可通过设计器拖拽或代码创建)
    1. 在代码中赋值颜色,示例:
progressBar.ForeColor = Color.Blue;

注意:若ProgressBar的Style属性设为Marquee,自定义颜色可能不生效,建议改为Continuous或Blocks。

二、基于特定条件动态修改颜色

在实际场景中,常需要根据业务条件(如密码强度、任务完成状态)动态切换进度条颜色,以下以密码强度指示为例说明实现步骤:

实现思路

  1. 监听密码输入框的文本变化事件
  2. 根据密码的长度、包含字符类型等规则计算强度等级
  3. 对应不同等级设置进度条的颜色和进度值

示例代码

假设窗体中有TextBox(命名为txtPassword)和ProgressBar(命名为pbPasswordStrength),编写文本变化事件处理逻辑:

private void txtPassword_TextChanged(object sender, EventArgs e)
{
    string password = txtPassword.Text;
    int strengthLevel = 0;
    Color targetColor = Color.Red;

    // 密码强度判定规则
    if (password.Length >= 6) strengthLevel++;
    if (password.Any(char.IsDigit)) strengthLevel++;
    if (password.Any(c => !char.IsLetterOrDigit(c))) strengthLevel++;
    if (password.Length >= 10) strengthLevel++;

    // 根据强度设置颜色与进度
    switch (strengthLevel)
    {
        case 0:
        case 1: // 弱强度
            targetColor = Color.Red;
            pbPasswordStrength.Value = 25;
            break;
        case 2: // 中强度
            targetColor = Color.Gold;
            pbPasswordStrength.Value = 50;
            break;
        case 3:
        case 4: // 高强度
            targetColor = Color.Green;
            pbPasswordStrength.Value = 100;
            break;
    }

    pbPasswordStrength.ForeColor = targetColor;
    pbPasswordStrength.Style = ProgressBarStyle.Continuous;
}

三、自定义控件解决系统样式限制

若系统启用了视觉样式(默认Application.EnableVisualStyles()),原生ProgressBar的ForeColor可能不生效,此时可通过自定义ProgressBar控件重绘实现:

自定义ProgressBar控件代码

public class CustomProgressBar : ProgressBar
{
    public CustomProgressBar()
    {
        // 开启用户自定义绘制
        SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        var clientRect = ClientRectangle;
        var g = e.Graphics;

        // 绘制背景
        g.FillRectangle(new SolidBrush(BackColor), clientRect);

        // 计算进度宽度
        var progressWidth = (int)(clientRect.Width * ((double)Value / Maximum));
        progressWidth = progressWidth == 0 ? 1 : progressWidth; // 避免进度为0时无显示

        // 绘制进度条
        g.FillRectangle(new SolidBrush(ForeColor), 0, 0, progressWidth, clientRect.Height);

        // 绘制边框(可选)
        g.DrawRectangle(Pens.DarkGray, 0, 0, clientRect.Width - 1, clientRect.Height - 1);
    }
}

使用方法

  1. 将上述代码添加到项目中,编译后自定义控件会出现在工具箱中
  2. 拖拽CustomProgressBar到窗体,即可自由设置ForeColor和BackColor,不受系统样式影响

内容的提问来源于stack exchange,提问作者Harshana Jayasekara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:07:25