6
votes

I've created a WinForms User Control. I read a couple of places something about GotFocus() and LostFocus() events, yet my user control doesn't provide these events in the Events part of the Properties window.

I even tried typing override to see if these event handlers would come up but they don't. I can't find them anywhere.

So I created my own methods with these names, and then I get the following error:

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

What the heck is going on here. If GotFocus() already exists, why can't I find it and use it?

4
It's Microsoft's way of saying they prefer you to use the Enter and Leave events instead. GotFocus and LostFocus ended up getting marked Browsable(false) to encourage that.LarsTech

4 Answers

11
votes

It looks like from the MSDN Documentation that they are there inherited from Control, but are not encouraged to be used. They want you to use the Enter and Leave Events.

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.

That said you can get access to them as User1718294 suggested with the += or you can Override the OnGotFocus and OnLostFocus Event.

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

protected override void OnGotFocus(EventArgs e)
{
    base.OnGotFocus(e);
}
4
votes

GotFocus is an event that is already exists. What you are trying to do is to create a method that is called "GotFocus", since an event with the same name is already exists, you can't create your method with this name.

In order to "use" an event, you have to register a function to it, like so:

mycontrol.GotFocus += mycontrol_GotFocus;

Now just add this method, to handle the event:

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

When you inherit from one class and you're not sure of what methods/properties it contains you can simply look at the base object

Type 'base.' inside a method body and autocomplete will show you the base methods.

0
votes

Using Visual Studio 2010

Use Activated event when focus is gained and Deactivate event when focus is lost. Here is the following example code which changes Form Name when it gets focus. (filename is a string member of Form1 class which extends Form class)

private void Form1_Activated(object sender, EventArgs e)
    {
        if (fileName == "Untitled")
            this.Text = fileName + "- Text Editor";
        else this.Text = fileName + "- Text Editor";
    }