2017-09-16 38 views
-1

现在,这是我使用的程序进入/离开:如何在其他地方点击时离开文本框?

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

顺便说一句,这只是我使用的水印的一个例子。可能还有其他情况。 – Qedized

+2

该功能内置于Windows。研究提示横幅 – Plutonix

+0

你应该通过控制焦点来做到这一点,比如当点击背景时将ContainerControl.ActiveControl属性设置为当前表单。 – saeed

回答

1

而不是使用Enter和Leave的TextBox事件,使用GotFocusLostFocus事件,其次要在文本框中使用形式的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; 
     } 
    } 

最后,窗体的Click事件为

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 
    } 

此替代方法可能对您有所帮助。

+0

它真的帮了我。感谢您花时间! :) – Qedized

+0

您可以接受为答案来关闭此问题 –

0

,你也可以使用这个

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

仅限代码答案是因为他们不解释他们如何解决问题。请更新你的答案,以解释这个问题已经有了什么改进。请复习[我如何写出一个好答案](https://stackoverflow.com/help/how-to-answer)。 – FluffyKitten

相关问题