0

I have a MDImain(Form1) for that handles a custom event generated by children. When I create an instance of a child form I attach the child event to the parent handler. All works great parent catches the event generated by the child. Code in the parent looks like this.

ChildForm instanceChildForm = new ChildForm();
instanceChildForm.Feedback += new EventHandler<feedback>(MainMessageHandler);

then I show the child form... (The Main message handler is in the parent form)

Now I want my child form to show a third form call it child 2. It's instantiated from childForm, but I want the parent MDI to still catch this event. How to I get the vent back to the mdi parent.

All I can think of would be to make the MainMessageHandler routine public on the main form, but then I still need a ref to the main form ... child3.parent = child2parent then attach the event like so:

ChildForm2 instanceChildForm2 = new ChildForm2();
instanceChildForm2.Feedback += new EventHandler<feedback>(this.parent.MainMessageHandler);

or something like that.

OR would this be a good use for a delegate kind of thing? If so I'm not sure how to pull that off.

Thanks for your help !

svick
  • 236,525
  • 50
  • 385
  • 514
pStan
  • 1,084
  • 3
  • 14
  • 36

1 Answers1

1

There's a million and one ways to do it. In my opinion, in any Windows app, you need to be aware of all the forms, their state and be able to past messages between them without creating dependencies. Something like:

public class FormManager
{
    List<Form> _forms = new List<Form>();

    public void CreateForm<T>() where T : Form, new()
    {
        var form = new T();
        _forms.Add(form);
        AttachEvents(form);
        form.Show();
    }

    ...methods for attaching events, responding to them, and DETACHING on form.Closed
}

instead of new() ing up forms, you use FormManager.CreateForm<Form1>();

Now, when one of your forms raises an event, you have access to all the forms, both parent and children, and you can make decisions about what to do about that event. You can make those decisions in the FormManager if you want it to be smart, or you can push it down to the forms themselves.

Steven P
  • 1,956
  • 1
  • 16
  • 17
  • This looks like it might get complicated if you are passing values to forms using constructors. – pStan Mar 12 '12 at 16:24
  • You could also add a Register method that accepts a preconstructed form. The point remains the same - if you have a central repository of forms, you can attach events and make decisions. – Steven P Mar 12 '12 at 20:37
  • The Register method sounds good. I have a custom base form that all other forms inherit from. I could register the form after it's loaded, then connect any additional events. Thanks for your ideas. – pStan Mar 13 '12 at 16:18