I have a WinForms project with a main topmost form from which a non-modal dialog is displayed. I need to hide (not close) the dialog if it loses the input focus - no matter what was the reason (the user clicked the main form, switched to another app, etc). The following bare part of the project source code shows what is going on:
public partial class MainForm : Form
{
Form _dialog = new Form();
public MainForm()
{
InitializeComponent();
this.TopMost = true;
this.Text = "Main Form";
_dialog.Text = "Dialog";
_dialog.Owner = this;
_dialog.TopMost = true;
_dialog.Deactivate += Dialog_Deactivate;
_dialog.FormClosing += Dialog_FormClosing;
}
private void Dialog_Deactivate(object sender, EventArgs e)
{
_dialog.Hide();
}
private void Dialog_FormClosing(object sender, FormClosingEventArgs e)
{
_dialog.Hide();
e.Cancel = true;
}
private void ButtonShowDialog_Click(object sender, EventArgs e)
{
_dialog.Show();
}
}
The main problem I am trying to solve is the following. If the user opened the dialog and clicks the main form like I depicted on the following screenshot
, the dialog becomes hidden as expected, but the main form loses the focus and another app that was previously active becomes active in the background - the Windows Explorer on the next screenshot:
Is it a known issue in Windows or WinForms? How to cause the main form not to lose the focus in this construction?


The issue seems to be that when the Main Form is clicked, it triggers a
WM_WINDOWPOSCHANGINGevent. Since the child dialog is open, thehwndInsertAfterhandle is the child dialog. But then in theDialog_Deactivatethe child dialog is hidden, causing the Main Form to fall behind all the other windows because thehwndInsertAfterhandle is no longer a visible window.Possible solutions are 1) set the child dialog owner to null before calling
Hide()or 2) use a different event, likeLostFocus, i.e: