2012-04-21 268 views
11

我想添加一個甚至到TextBox當它有焦點。我知道我可以用簡單的textbox1.Focus來做到這一點,並檢查布爾值...但我不想這樣做。TextBox焦點的WinForms事件?

這裏是我想做到這一點:

this.tGID.Focus += new System.EventHandler(this.tGID_Focus); 

我不知道,如果事件處理程序是這樣做的正確的方式,但我知道,這是行不通的。

+9

使用Enter事件。 – 2012-04-21 01:08:08

回答

16

您正在尋找GotFocus活動。還有一個LostFocus事件。

textBox1.GotFocus += textBox1_GotFocus; 
+0

這就是我正在尋找的tyvm。 – mawburn 2012-04-21 02:45:54

+0

很高興我能幫到你。 – lordcheeto 2012-04-21 07:21:12

+0

不要通過鼠標單擊工作在焦點上 – Geograph 2016-10-04 07:54:10

12
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 article描述了被稱爲及順序不同的事件。你可能會看到更好的事件。

7

我上投漢斯帕桑特的評論,但它確實應該是一個答案。我正在使用3.5 .NET環境中的Telerik UI,並且RadTextBoxControl上沒有GotFocus事件。我不得不使用Enter事件。

textBox1.Enter += textBox1_Enter; 
+0

事實上,所有控件都有一個'GotFocus'事件,但它沒有[設計器支持](http://stackoverflow.com/a/36124027/3110834)。建議使用「Enter」。 – 2016-03-21 06:18:11