C# 单击其他位置时如何保留文本框?

C# 单击其他位置时如何保留文本框?,c#,winforms,focus,C#,Winforms,Focus,现在,这是我用于进入/离开的程序: private void tbFullName_Enter(object sender, EventArgs e) { if (tbFullName.Text == "Full name") { tbFullName.Text = ""; tbFullName.ForeColor = Color.Black; } } private

现在,这是我用于进入/离开的程序:

    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
    }

使用
GotFocus
LostFocus
事件,而不是使用
TextBox
的Enter和Leave事件,其次要从文本框中退出,请使用表单的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;
        }
    }
最后,窗体的单击事件为

    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
    }

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

顺便说一句,这只是我使用的水印的一个示例。可能还有其他情况。该功能内置于Windows中。搜索提示横幅您应该通过控制焦点来完成此操作,例如单击“背景”时,将ContainerControl.ActiveControl属性设置为当前表单。不鼓励只回答代码,因为它们不会解释如何解决问题。请更新您的答案,解释这是如何改进此问题已有的答案的。请复习。它真的帮助了我。谢谢你抽出时间!:)