我目前正在c#Visual Studio中设计一个注册表单,我遇到了一个问题。从第一张图片中可以看出,我有两个带有自己默认文本的文本框。之后,我为它们创建了一个进入和离开事件处理程序。 我的目标是当用户点击文本框时,默认文本将消失,用户可以开始输入密码,该密码将替换为星号。当用户离开文本框而不输入任何值时,将再次显示默认文本。但是,现在我的问题是默认文本将转换为星号,这不是我想要的。 这是我的代码示例
private void txtPassword_Enter(object sender, EventArgs e)
{
if (txtPassword.Text == "Enter a password...")
{
txtPassword.Text = "";
txtPassword.PasswordChar = '*'; // Mask characters of a password to asterisk.
txtPassword.ForeColor = Color.Black;
}
}
private void txtPassword_Leave(object sender, EventArgs e)
{
if(txtPassword.Text == "")
{
txtPassword.Text = "Enter a password...";
txtPassword.ForeColor = Color.Gray;
}
}
您需要重置PasswordChar
才能阻止文本框屏蔽文本。
您的Leave
事件处理程序应如下所示:
private void txtPassword_Leave(object sender, EventArgs e)
{
if(txtPassword.Text == "")
{
txtPassword.PasswordChar = '\0'; // Note this line!
txtPassword.Text = "Enter a password...";
txtPassword.ForeColor = Color.Gray;
}
}