【问题标题】:C# progress bar change colorC#进度条改变颜色
【发布时间】:2011-12-23 09:31:27
【问题描述】:

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

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 似乎不起作用。有什么帮助吗?谢谢。

【问题讨论】:

  • 您使用的是 WinForms、ASP.NET、WPF、Silverlight 吗?
  • 如果你手动设置,而不是用这个方法,这样行吗?
  • 我不能代表 ASP.NET 等,但对于 WinForms 和 WPF(使用标准的进度条),我认为这涉及对相当复杂的控件进行子类化。

标签: c# colors progress-bar


【解决方案1】:

从您的应用程序中查找并删除 Application.EnableVisualStyles();

你可以从here找到很多例子

【讨论】:

    【解决方案2】:

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

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

    相反,给每个条件一个分数,然后根据总分选择你的颜色:

        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++ 尤其容易出现错误软件。)

    【讨论】:

    • 这不是关于 ProgressBar 的原始问题。
    【解决方案3】:

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

     Application.EnableVisualStyles();
    

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

    【讨论】:

    • 注 1:这也会从所有其他控件(例如 TextBox、Button)中删除视觉样式。注2:问题是关于WinForms的。
    • 如果这是WinForms,它实际上是可能的。见this answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多