RichTextBox的密码字符

时间:2010-12-15 15:25:12

标签: c# .net winforms

我正在使用基于RichTextBox的透明自定义控件。是否有任何方法可以像常规TextBox控件那样使用密码char支持。

3 个答案:

答案 0 :(得分:5)

这很简单,RTB实际上实现了对密码输入的支持。它只是没有暴露在.NET包装器中。在项目中添加一个新类并粘贴下面显示的代码。编译。将新控件从工具箱顶部拖放到表单上。

using System;
using System.Windows.Forms;

class RichPassword : RichTextBox {
    protected override CreateParams CreateParams {
        get {
            // Turn on ES_PASSWORD
            var cp = base.CreateParams;
            cp.Style |= 0x20;
            return cp;
        }
    }
}

答案 1 :(得分:0)

是的,有办法。您必须在绘制按键之前拦截按键(查找PreviewKeyDown或类似事件)并将其更改为星号(*)。但是你还需要实现逻辑来管理真实的字符串。

注意我同意Cody Gray的评论。

答案 2 :(得分:-1)

这对我有用并解决了目的。

Public Class RichPassword
    Inherits RichTextBox
    Private Const ES_PASSWORD = 32  
    Protected Overrides ReadOnly Property CreateParams As CreateParams
        Get
            Dim CP = MyBase.CreateParams
            CP.Style = CP.Style Or 32
            Return CP
        End Get
    End Property
End Class