C#进度条改变颜色

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

using System.Text.RegularExpressions; using System.Drawing; using System.Drawing.Drawing2D; var PassChar = txtPass.Text; 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, @"[az]") && Regex.IsMatch(PassChar, @"[AZ]")) pgbPass.ForeColor = Color.Orange; if (Regex.IsMatch(PassChar, @"[!@#\$%\^&\*\?_~\-\(\);\.\+:]+")) pgbPass.ForeColor = Color.Red; 

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

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

  Application.EnableVisualStyles(); 

或使用一些自定义进度条控件,如http://www.codeproject.com/KB/cpp/colorprogressbar.aspx

查找并删除Application.EnableVisualStyles(); 从你的应用。

你可以从这里找到很多例子

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

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

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

  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, @"[az]") && Regex.IsMatch(PassChar, @"[AZ]")) 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 ++尤其容易出错。)