简体   繁体   中英

c# How do I catch Windows Form Events in user control?

I have made a user control for search. In the time of searching a popup will open. Now I want to access Form_Resize and Form_LocationChanged event from the user control.

In Control constructor, you have to subscribe to ParentChanged event of the control to know when you can get your controls current parent.

public YourControl()
{
    InitializeComponent();
    ParentChanged += OnParentchanged;
}

private void OnParentchanged(object sender, EventArgs e)
{
    // maybe get Form istead of just parent control
    Parent.Resize += OnParentResize;
    Parent.LocationChanged += OnParentLocationChanged;
}

Then you have to subscribe to the form's events that you need. The thing is, that Parent of your control might be another control, so you may want to recursively search all Parents until it's form. It is just not that really that clear what do you want to achieve.

Also, remember that you have unsubscribe from events of a previous parent if it changes. But that's another and a very tricky question.

EDIT:
You don't need to recursively search for the form by yourself, there is a FindForm() method, that was mentioned by @jmcilhinney

Every control has a FindForm method that will return the form that contains the control, even if there are other controls in between in the hierarchy. Once you have a reference to the form, you can handle its events in exactly the same way as you would any other object's at run time.

The Parent object might be null if you try to access it from the constructor. What I had to do was add the reference in the Load event for the UserControl.

private void CustomControl_Load(object sender, EventArgs e)
{        
    ParentChanged += OnParentChanged;
}

private void OnParentChanged(object sender, EventArgs e)
{
    Parent.Resize += OnParentResize;
    Parent.LocationChanged += OnParentLocationChanged;
    // More events or
    // Do Something...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM