Avoid that strange “Form going to background” effect in WinForms

Someone asked me yesterday about a strange effect he was getting in a WinForms application.

Scenario:

  1. Form1 is the main form of the application
  2. Form2 is a child form shown sometimes to make additional operations. This form is shown using the Show() method, not the ShowDialog() method. I´m not sure if this affects this specific situation, but in his program, Form2 is forced to never be closed (except when app exiting), so it can be reopened whenever the user wants, without loosing information. This way, when user closes the form, it´s in fact being hidden, not closed.

Symptoms:

Apparently sometimes, when user closes Form2 (actually hides it), the focus doesn´t come back to the main form. Instead, Form1 is minimized, what is very frustrating from the user experience point of view.

Solution:

What looked like a random behavior, it is in fact due to Form2 opening additional modal dialogs, like MessageBoxes, and setting their owner to himself (Form2). Something like this:

class Form2

{

MessageBox.Show(this, “Hello”, “World”…);

}

The solution is to set the MessageBox´s Owner to Form1 (the main form), instead of Form2, like this:

MessageBox.Show(this.Owner, “Hello”, “World”…);

And that´s it ;)