Can't Find GotFocus()/LostFocus() in My User Control

15,885

Solution 1

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);
}

Solution 2

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.");
}
Share:
15,885
Jonathan Wood
Author by

Jonathan Wood

Software developer working out of Salt Lake City, UT. Independent consultant as SoftCircuits. Currently looking for new job opportunities. I've published a number of open source libraries for .NET on NuGet and GitHub. Interests include playing bass and guitar and hiking with my dog.

Updated on June 14, 2022

Comments

  • Jonathan Wood
    Jonathan Wood almost 2 years

    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?