单击其他地方时如何离开文本框?

How to leave a textbox when clicked somewhere else?

现在,这是我用于 enter/leave:

的程序
    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;
        }
    }

只有当我专注于另一个元素时它才会离开。我希望它在我单击背景或其他任何地方时离开。我该怎么做?

你也可以用这个

private void Form1_Click(object sender, EventArgs e)
    {
        //your code here
    }

不使用 TextBox 的 Enter 和 Leave 事件,而是使用 GotFocusLostFocus 事件,其次从文本框离开使用 Form 的 Click 事件调用 LostFocus 事件。但在调用它之前禁用文本框并在调用启用文本框之后像下面的代码

在表单中初始化事件

    public Form()
    {
        InitializeComponent();

        //attach the events here
        tbFullName.GotFocus += TbFullName_GotFocus;
        tbFullName.LostFocus += TbFullName_LostFocus;
    }

像这样的文本框事件

    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;
        }
    }

最后,Form的点击事件为

    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
    }

此解决方法可能对您有所帮助。