# 如何：使用 Windows 窗体 TextBox 控件创建密码文本框How to: Create a Password Text Box with the Windows Forms TextBox Control

### 创建密码文本框To create a password text box

1. TextBox控件PasswordChar的属性设置为特定字符。Set the PasswordChar property of the TextBox control to a specific character.

PasswordChar属性指定文本框中显示的字符。The PasswordChar property specifies the character displayed in the text box. 例如, 如果希望在 "密码" 框中显示星号, 请在 "属性窗口PasswordChar中为属性指定" * "。For example, if you want asterisks displayed in the password box, specify * for the PasswordChar property in the Properties window. 然后, 无论用户在文本框中键入什么字符, 都将显示一个星号。Then, regardless of what character a user types in the text box, an asterisk is displayed.

2. 可有可无MaxLength设置属性。(Optional) Set the MaxLength property. 属性确定在文本框中键入的字符数。The property determines how many characters can be typed in the text box. 如果超过了最大长度, 系统会发出嘟嘟声, 文本框不接受任何其他字符。If the maximum length is exceeded, the system emits a beep and the text box does not accept any more characters. 请注意, 你可能不希望这样做, 因为密码的最大长度可能会被尝试猜测密码的黑客使用。Note that you may not wish to do this as the maximum length of a password may be of use to hackers who are trying to guess the password.

下面的代码示例演示如何初始化一个文本框, 该文本框将接受长度最长为14个字符的字符串, 并显示星号来替换字符串。The following code example shows how to initialize a text box that will accept a string up to 14 characters long and display asterisks in place of the string. InitializeMyControl过程不会自动执行; 必须调用它。The InitializeMyControl procedure will not execute automatically; it must be called.

重要

如果使用PasswordChar文本框上的属性, 则可帮助确保其他人在观察用户输入密码时不能确定用户的密码。Using the PasswordChar property on a text box can help ensure that other people will not be able to determine a user's password if they observe the user entering it. 此安全措施不包含任何类型的密码, 无论是由于应用程序逻辑造成的, 都不会出现任何类型的密码。This security measure does not cover any sort of storage or transmission of the password that can occur due to your application logic. 由于输入的文本未以任何方式进行加密, 因此应将其视为任何其他机密数据。Because the text entered is not encrypted in any way, you should treat it as you would any other confidential data. 即使它不是这样, 也仍会将密码视为纯文本字符串 (除非您已经实现了一些附加的安全措施)。Even though it does not appear as such, the password is still being treated as a plain-text string (unless you have implemented some additional security measure).

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

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

private:
void InitializeMyControl()
{
// Set to no text.
textBox1->Text = "";
// The password character is an asterisk.