1. 程式人生 > >C# 文字框輸入提示

C# 文字框輸入提示

在我們窗體程式設計時,有時需要實現輸入文字框的提示效果,實現方法如下:
1、窗體中的文字框名稱分別為txtName和txtPwd

2、控制其事件:
#region 文字框輸入提示
Boolean textboxHasText = false;//判斷輸入框是否有文字
private void txtName_Enter(object sender, EventArgs e)
{
if (textboxHasText == false)
{
txtName.Text = “”;
txtName.ForeColor = Color.Black;
}
}
private void txtName_Leave(object sender, EventArgs e)
{
if (txtName.Text == “”)
{
txtName.Text = “請輸入使用者名稱”;
txtName.ForeColor = Color.LightGray;
textboxHasText = false;
}
else
{
textboxHasText = true;
}
}
Boolean textboxHasText2 = false;//判斷輸入框是否有文字
private void txtPwd_Enter(object sender, EventArgs e)
{
if (textboxHasText2 == false)
{
txtPwd.Text = “”;
txtPwd.PasswordChar = (char)42;
txtPwd.ForeColor = Color.Black;
}
}
private void txtPwd_Leave(object sender, EventArgs e)
{
if (txtPwd.Text == “”)
{
txtPwd.Text = “請輸入密碼”;
txtPwd.ForeColor = Color.LightGray;
textboxHasText2 = false;
txtPwd.PasswordChar = ‘\0’;
}
else
{
textboxHasText2 = true;
}
}
#endregion
3、實現效果:
實現效果