C#进度条改变颜色

时间:2011-11-07 05:21:10

标签: c# colors progress-bar

我正在尝试更改进度条的颜色,我将其用作密码强度验证器。例如,如果所需的密码较弱,则进度条将变为黄色,如果为中,则为绿色。坚强,橙色。非常强烈,红色。就是这样的。这是密码强度验证器的代码:

using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Drawing2D;

var PassChar = txtPass.Text;

        if (txtPass.Text.Length < 4)
        pgbPass.ForeColor = Color.White;
        if (txtPass.Text.Length >= 6)
        pgbPass.ForeColor = Color.Yellow;
        if (txtPass.Text.Length >= 12)
        pgbPass.ForeColor = Color.YellowGreen;
        if (Regex.IsMatch(PassChar, @"\d+"))
        pgbPass.ForeColor = Color.Green;
        if (Regex.IsMatch(PassChar, @"[a-z]") && Regex.IsMatch(PassChar, @"[A-Z]"))
        pgbPass.ForeColor = Color.Orange;
        if (Regex.IsMatch(PassChar, @"[!@#\$%\^&\*\?_~\-\(\);\.\+:]+"))
        pgbPass.ForeColor = Color.Red;

pgbPass.ForeColor = Color.ColorHere似乎不起作用。有帮助吗?感谢。

3 个答案:

答案 0 :(得分:23)

除非视觉样式已禁用,否则无法在c#中更改进度条颜色。尽管IDE提供更改颜色,但您将看不到颜色更改,因为进度条将占用当前操作系统的视觉样式。您可以选择禁用整个应用程序的视觉样式。要执行此操作,请转到程序的起始类并从代码中删除此行

 Application.EnableVisualStyles();

或使用这样的自定义进度条控件 http://www.codeproject.com/KB/cpp/colorprogressbar.aspx

答案 1 :(得分:4)

从您的申请中查找并删除Application.EnableVisualStyles();

您可以在here

中找到许多示例

答案 2 :(得分:3)

红色往往表示错误或麻烦 - 请重新考虑使用红色表示“强密码”。

此外,由于您根据可能的多次匹配多次更新颜色,因此您的颜色将不会像您希望的那样一致。

相反,为每个条件指定得分,然后根据总得分选择颜色:

    int score = 0;

    if (txtPass.Text.Length < 4)
        score += 1;
    if (txtPass.Text.Length >= 6)
        score += 4;
    if (txtPass.Text.Length >= 12)
        score += 5;
    if (Regex.IsMatch(PassChar, @"[a-z]") && Regex.IsMatch(PassChar, @"[A-Z]"))
        score += 2;
    if (Regex.IsMatch(PassChar, @"[!@#\$%\^&\*\?_~\-\(\);\.\+:]+"))
        score += 3;

    if (score < 2) {
       color = Color.Red;
    } else if (score < 6) {
       color = Color.Yellow;
    } else if (score < 12) {
       color = Color.YellowGreen;
    } else {
       color = Color.Green;
    }

请注意使用else-if构造有时比语言提供的switchcase语句更容易。 (特别是C / C ++的软件容易出错。)

相关问题