C# 文本框焦点的 WinForms 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10255278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WinForms event for TextBox focus?
提问by mawburn
I want to add an even to the TextBoxfor when it has focus. I know I could do this with a simple textbox1.Focusand check the bool value... but I don't want to do it that way.
TextBox当它有焦点时,我想为它添加一个偶数。我知道我可以用一个简单的方法来做到这一点textbox1.Focus并检查 bool 值......但我不想那样做。
Here is how I would like to do it:
这是我想怎么做:
this.tGID.Focus += new System.EventHandler(this.tGID_Focus);
I'm not sure if EventHandler is the correct way to do this, but I do know that this does not work.
我不确定 EventHandler 是否是正确的方法,但我知道这行不通。
采纳答案by lordcheeto
You're looking for the GotFocus event. There is also a LostFocus event.
您正在寻找 GotFocus 事件。还有一个 LostFocus 事件。
textBox1.GotFocus += textBox1_GotFocus;
回答by Michael J. Gray
this.tGID.GotFocus += OnFocus;
this.tGID.LostFocus += OnDefocus;
private void OnFocus(object sender, EventArgs e)
{
MessageBox.Show("Got focus.");
}
private void OnDefocus(object sender, EventArgs e)
{
MessageBox.Show("Lost focus.");
}
This should do what you want and this articledescribes the different events that are called and in which order. You might see a better event.
这应该可以满足您的需求,本文介绍了调用的不同事件以及调用顺序。你可能会看到一个更好的事件。
回答by WEFX
I up-voted Hans Passant's comment, but it really should be an answer. I'm working on a Telerik UI in a 3.5 .NET environment, and there is no GotFocus Event on a RadTextBoxControl. I had to use the Enter event.
我对 Hans Passant 的评论投了赞成票,但这确实应该是一个答案。我正在 3.5 .NET 环境中处理 Telerik UI,RadTextBoxControl 上没有 GotFocus 事件。我不得不使用 Enter 事件。
textBox1.Enter += textBox1_Enter;
回答by user3029478
Here is how you wrap it and declare the handling function, based on Hans' answer.
以下是根据 Hans 的回答,如何包装它并声明处理函数。
namespace MyNameSpace
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
txtSchedNum.Enter += new EventHandler(txtSchedNum_Enter);
}
protected void txtSchedNum_Enter(Object sender, EventArgs e)
{
txtSchedNum.Text = "";
}
}
}

