如何:使用 Windows 窗体 TextBox 控件创建密码文本框 .NET Framework 2.0 其他版本 密码框是一种 Windows 窗体文本框,它在用户键入字符串时显示占位符。 创

来源:互联网 发布:linux系统装informix 编辑:程序博客网 时间:2024/06/05 00:07

如何:使用 Windows 窗体 TextBox 控件创建密码文本框

.NET Framework 2.0
其他版本

密码框是一种 Windows 窗体文本框,它在用户键入字符串时显示占位符。

创建密码文本框

  1. 将 TextBox 控件的 PasswordChar 属性设置为某个特定字符。

    PasswordChar 属性指定在文本框中显示的字符。例如,如果希望在密码框中显示星号,请在“属性”窗口中将 PasswordChar 属性指定为“*”。然后,无论用户在文本框中键入什么字符,都显示为星号。

  2. 设置 MaxLength 属性(可选)。此属性确定可在文本框中键入多少字符。如果超过了最大长度,系统会发出声响,且文本框不再接受任何字符。注意,您可能不想设置此属性,因为黑客可能会利用密码的最大长度来试图猜测密码。

    下面的代码示例演示了如何初始化一个文本框,此文本框可接受最长 14 个字符的字符串,并显示星号来替代该字符串。InitializeMyControl 过程不会自动执行,而需进行调用。

    Security note安全注意

    使用文本框上的 PasswordChar 属性可帮助确保实现以下功能:用户输入密码时如有其他人在观看,他们将无法知道输入的密码。此安全措施未涵盖可能会根据应用程序逻辑的需要而发生的任何种类的密码存储或传输。因为输入的文本未以任何方式进行加密,所以您应该像处理任何其他机密数据一样处理它。即使密码未显示为纯文本,它也仍被视为纯文本字符串(除非您已实施了其他安全措施)。

    VB
    Private Sub InitializeMyControl()   ' Set to no text.   TextBox1.Text = ""   ' The password character is an asterisk.   TextBox1.PasswordChar = "*"   ' The control will allow no more than 14 characters.   TextBox1.MaxLength = 14End Sub

    C#
    private void InitializeMyControl(){   // Set to no text.   textBox1.Text = "";   // The password character is an asterisk.   textBox1.PasswordChar = '*';   // The control will allow no more than 14 characters.   textBox1.MaxLength = 14;}

    J#
    private void InitializeMyControl() {   // Put some text into the control first.   textBox1.set_Text("This is a TextBox control.");        // Set to no text.   textBox1.set_Text("");   // The password character is an asterisk.   textBox1.set_PasswordChar('*');   // The control will allow no more than 14 characters.   textBox1.set_MaxLength(14);}

    C++
    private:   void InitializeMyControl()   {      // Set to no text.      textBox1->Text = "";      // The password character is an asterisk.      textBox1->PasswordChar = '*';      // The control will allow no more than 14 characters.      textBox1->MaxLength = 14;   }
阅读全文
0 0
原创粉丝点击