My application loses focus when closing a window

I have two simple forms, one of which contains a grid and a button. When I press the button, my application starts to perform a long operation. While it works, I show another form containing a progress bar. I open it like this:

_busyWindow.ShowDialog(); 

And determined

 public partial class BusyWindow : DevExpress.XtraEditors.XtraForm { public BusyWindow() { InitializeComponent(); } private void BusyWindow_FormClosing(object sender, FormClosingEventArgs e) { this.Hide(); e.Cancel = true; // this cancels the close event. } } 

When the operation is completed, I hide the form as follows

 if (ended) _busyWindow.Hide(); 

It works great. The problem is that when I close the second form (the same closing code), it also closes fine, but my main GUI loses focus. For example, if I have Firefox that opens behind the application, then Firefox gets the focus.

This only happens when I close the second form when busyWindow is opened and not when it doesn’t (if I open the form, I close it without clicking the button, then the main GUI don’t lose focus).

Do you know what is happening or where can I try to search?

+4
source share
2 answers

There may be two possible solutions in your main window:

// Edited: The main window in the example below is a window with a grid and a button.

  • Since you are displaying a busy window through ShowDialog() , try setting the window owner as follows: _busyWindow.ShowDialog(this); . I used to run into a similar problem, and it worked for me. Since you will indicate the owner of busyWindow when it closes, it will return focus back to its owner, i.e. your main window

  • In case the above method does not work (it should, as it worked for me), you could try to transfer the main window link to busyWindow, and then close the main window focus, close it, Example:

_busyWindow.MyMainWindow = this; //MyMainWindow references mainWindow of your app _busyWindow.ShowDialog();

And the following in FormClosing of busyWindow:

private void BusyWindow_FormClosing(object sender, FormClosingEventArgs e)

 { this.Hide(); e.Cancel = true; // this cancels the close event. MainWindow.Focus(); } 

code>

See if this works. The first solution should work.

Hope this helps.

Thanks and happy window!

+3
source

Just set the child window to Owner = null before closing

+1
source

All Articles