Tech Blog‎ > ‎

.NET Winforms - Application loses focus when a window is closed

posted Sep 21, 2012, 12:27 PM by Victor Zakharov
I have a main form which is an MDI parent and a modal form, which is a progress dialog. When loading is completed, an MDI child is opened. If it cannot be completed, an error message shows up with user prompt. Problem is if user takes action, and the modal form is closed, the focus is switched to the application, which was active before my application was started. In my case it was Visual Studio 2010. I did not find a solution or why it happens, but here is a workaround - implement the following FormClosing handler (or add to your existing implementation, if you have one):

Private Sub frmSelectTable_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
  Me.Hide()
End Sub

The solution was inspired by this question @ stackoverflow.
Comments