2012-11-13 27 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类)

​​
相关问题