-1

I have two forms. I show my second form with this code:

Form2 f = new Form2();
f.ShowDialog();

I need to understand when focus returns to main form. I tried Activate event but that's not it.

John Conde
  • 217,595
  • 99
  • 455
  • 496
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48

2 Answers2

4

The call to ShowDialog() is blocking the parent form.
When your code exit from ShowDialog() your current form become active again,

For example:

using(Form2 f = new Form2())
{
    // At the moment of the call of ShowDialog, the Net Framework start its work to
    // pass the focus to the first control in the Form2 instance
    if(DialogResult.OK == f.ShowDialog())
    {
        // Form confirmed, do your stuff
    }
}

// At the end of the using block the parent form is again the active form with the focus on
// the button that has started this process (or the last control that had focus)
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thank you. It worked with a little change. `using (Form2 f = new Form2()){f.ShowDialog();}MessageBox.Show("Focus returned to main form");` – Masoud Keshavarz Aug 13 '12 at 14:05
1

When you type

Form2 f = new Form2();
f.ShowDialog();

it waits until you manually close the Form2 instance and then returns to the main form. This happens if you use ShowDialog() method.

In some cases, where you just want to pop-up another form for a fraction of a second and return to the main form you should use formInstance.Show() method. The Show() method does not wait for the second form to be closed, it executes immediately and passes the control to the next statement after the Show() statement.

Hope you understood it.

Robert Langdon
  • 855
  • 1
  • 11
  • 27