VB.NET如何修改TextBox控件中单行文本的字体和颜色(密码强度校验场景)
关于TextBox局部文本格式修改的解答
核心结论
标准WinForm TextBox控件不支持单独修改某一行或部分文本的字体、颜色属性,所有格式配置只会作用于控件内的全部文本,无法实现局部差异化格式效果。
替代方案
直接将你当前的txtChcekPass控件从TextBox替换为RichTextBox控件即可,RichTextBox原生支持富文本编辑,可选中任意范围的文本单独设置字体、颜色、字号等格式,完全适配你的密码强度提示场景。
适配代码示例
替换控件后,你可以参考如下写法实现局部格式自定义,同时修复了你原代码中的两处逻辑bug:
Function Checker(password As String) As String Dim i, l, c, k As Byte Dim array() As Char = password.ToCharArray() ' 修复原代码逻辑问题:符号分支错误累加循环变量i,会导致跳过后续字符校验 For idx = 0 To array.Length - 1 If Char.IsUpper(array(idx)) Then c += 1 ElseIf Char.IsLower(array(idx)) Then l += 1 ElseIf Char.IsNumber(array(idx)) Then k += 1 ElseIf Char.IsSymbol(array(idx)) Then i += 1 End If Next ' 先清空控件内容 pnlCheckPass.txtChcekPass.Clear() ' 若需要保留密码原文用默认格式展示,可先追加密码 pnlCheckPass.txtChcekPass.AppendText(password) ' 记录强度提示文本的起始位置 Dim tipStart As Integer = pnlCheckPass.txtChcekPass.TextLength Dim tipText As String = "" Dim tipColor As Color = Color.Black ' 修复原代码无效判断:将恒成立的2>=1改为小写字母校验l>=1 If i >= 2 And k >= 3 And l >= 1 And c >= 2 And password.Length >= 6 Then tipColor = Color.DarkGreen tipText = " - Very strong password" ElseIf k >= 3 And l >= 2 And c >= 2 And i >= 2 And password.Length >= 6 Then tipColor = Color.Green tipText = " - Strong password" ElseIf k >= 2 And i >= 1 And c >= 1 And password.Length >= 6 Then tipColor = Color.Orange tipText = " - Medium password" ElseIf k = 1 And i >= 1 And password.Length = 4 Then tipColor = Color.Red tipText = " - Weak password" ElseIf k = 1 Then tipColor = Color.DarkRed tipText = " - Very weak password" Else tipColor = Color.IndianRed tipText = " - Blank password" End If ' 追加强度提示文本 pnlCheckPass.txtChcekPass.AppendText(tipText) ' 选中提示文本部分单独设置格式 pnlCheckPass.txtChcekPass.Select(tipStart, tipText.Length) pnlCheckPass.txtChcekPass.SelectionFont = New Font("Microsoft YaHei UI", 10) pnlCheckPass.txtChcekPass.SelectionColor = tipColor ' 取消选中状态 pnlCheckPass.txtChcekPass.SelectionLength = 0 Return pnlCheckPass.txtChcekPass.Text End Function
补充说明
如果你不需要保留密码原文,仅需要展示强度提示,可跳过密码追加步骤,直接把强度提示文本赋值给RichTextBox后全选设置对应格式即可,改造成本极低。
内容的提问来源于stack exchange,提问作者Lasicak
相关产品推荐
相关产品推荐

