Search code examples
c#visual-studiomodal-dialogfocusparent-child

How to detect that a modal form is opened from a child form? (C# & VS2017)


Maybe it's a silly question but I can't find a solution.

I have an MDI form with multiple children. There is one that I could say is the main one.

To detect that the principal is no longer used and another child form is used I use the 'Leave' event which works very well.

The problem is when from the mdi form, a modal type (.ShowDialog ()) is executed, the Leave event doesn't happen in the child form.

Any suggestion or comment on how to get it is welcome.


Solution

  • I solved it this way:

    From the MDI form, from where the modal forms are called, I search for the child forms and if it is the "main" one, I call a public function that does the same as the Leave event of the "main" form:

    foreach (Form childform in this.MdiChildren)
    {
        if (childform.Name.Equals("MyMainForm"))
        {
            var formMain = (MyMainForm)childform;
            formMain.stopTimer();
        }
    }

    It may be a cumbersome solution, but it is functional.