2012-11-13 29 views
1

我創建了一個WinForms用戶控件。我讀了幾個關於GotFocus()LostFocus()事件的地方,但我的用戶控件不在屬性窗口的事件部分提供這些事件。在我的用戶控件中找不到GotFocus()/ LostFocus()

我甚至嘗試打字override看看這些事件處理程序是否會出現,但他們沒有。我無法在任何地方找到它們。

所以我創造了我自己的方法對這些名字,然後我得到以下錯誤:

Warning 1 'mynamespace.mycontrol.GotFocus()' hides inherited member 'System.Windows.Forms.Control.GotFocus'. Use the new keyword if hiding was intended.

到底是什麼怎麼回事。如果GotFocus()已經存在,爲什麼我找不到並使用它?

+0

這是說微軟的方式,他們更喜歡你使用Enter和Leave事件來代替。 GotFocus和LostFocus最終被標記爲Browsable(false)來鼓勵這一點。 – LarsTech

回答

5

它看起來像從MSDN Documentation,他們在那裏繼承控制,但不鼓勵使用。他們希望您使用輸入和離開事件。

Note The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing custom controls. Instead the Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events.

這就是說,你可以訪問他們作爲User1718294與+ =或者你可以重寫OnGotFocusOnLostFocus事件建議。

protected override void OnLostFocus(EventArgs e) 
{ 
    base.OnLostFocus(e); 
} 

protected override void OnGotFocus(EventArgs e) 
{ 
    base.OnGotFocus(e); 
} 
+0

是的,我看到他們有些沮喪。但我希望Intellisense在編輯器中輸入'override'後立即顯示出來。奇。謝謝。 –

+0

@JonathanWood Intellisense會給你'OnLostFocus'和'OnGotFocus'方法。 –

+0

D'oh,我想那是我錯過的。那麼'GotFocus'和'LostFocus'是公共事件,還有'OnGotFocus()'和'OnLostFocus()'我應該用的那些? (這些事件正在控件中處理。) –

3

GotFocus是一個已經存在的事件。 你要做的是創建一個名爲「GotFocus」的方法,因爲同名的事件已經存在,你不能用這個名字創建你的方法。

爲了「用」一個事件,你有一個函數註冊它,像這樣:

mycontrol.GotFocus += mycontrol_GotFocus; 

現在只需添加此方法,以處理該事件:

private void mycontrol_GotFocus(object sender, EventArgs e) 
{ 
    MessageBox.Show("Got focus."); 
} 
+0

我完全理解錯誤的含義。我的問題是,如果事件存在,爲什麼它不顯示在屬性窗口中或當我在編輯器中鍵入'override'?但是你是對的,當我在事件名稱後面使用'+ ='時,它會顯示出來。測試... –

0

當你從一個類繼承和你不知道什麼方法/屬性包含您可以簡單地看一下基本對象

類型「基地」。在方法體內部並且自動完成將向您顯示基本方法。

0

使用Visual Studio 2010

使用激活事件當焦點的獲得和停用事件丟失焦點時。 下面是以下示例代碼,它在獲取焦點時更改表單名稱。 (文件名是Form1類的串部件延伸Form類)

​​
相關問題