现在,这是我用于进入/离开的程序:
private void tbFullName_Enter(object sender, EventArgs e)
{
if (tbFullName.Text == "Full name")
{
tbFullName.Text = "";
tbFullName.ForeColor = Color.Black;
}
}
private void tbFullName_Leave(object sender, EventArgs e)
{
if (tbFullName.Text == "")
{
tbFullName.Text = "Full name";
tbFullName.ForeColor = SystemColors.InactiveCaption;
}
}
当我专注于另一个元素时它才会离开。当我点击背景或其他任何地方时,我希望它离开。我怎么能这样做?
答案 0 :(得分:1)
不使用TextBox
的Enter和Leave事件,而是使用GotFocus
和LostFocus
事件,其次从文本框中退出使用Form的Click事件来调用LostFocus事件。但在调用它之前禁用文本框并在调用启用文本框后如下面的代码
在表格初始化事件
public Form()
{
InitializeComponent();
//attach the events here
tbFullName.GotFocus += TbFullName_GotFocus;
tbFullName.LostFocus += TbFullName_LostFocus;
}
TextBox这样的事件
private void TbFullName_LostFocus(object sender, EventArgs e)
{
if (tbFullName.Text == "")
{
tbFullName.Text = "Full name";
tbFullName.ForeColor = SystemColors.InactiveCaption;
}
}
private void TbFullName_GotFocus(object sender, EventArgs e)
{
if (tbFullName.Text == "Full name")
{
tbFullName.Text = "";
tbFullName.ForeColor = Color.Black;
}
}
最后,将表格的点击事件视为
private void Form_Click(object sender, EventArgs e)
{
tbFullName.Enabled = false; //disable the textbox
TbFullName_LostFocus(sender, e); //call lost focus event
tbFullName.Enabled = true; //enable the textbox
}
此解决方法可能对您有所帮助。
答案 1 :(得分:0)
您也可以使用此
private void Form1_Click(object sender, EventArgs e)
{
//your code here
}