This seems like a simple goal here: to keep a Form showing, rather than hidden.
If you want the Form to remain visible, to not close unless the user closes it by clicking on its ControlBox, or by taking some other action that you then respond to by closing, or hiding, the Form: then I have to ask: why are you using 'ShowDialog ?
The whole purpose of ShowDialog is to present a Form "modally:" meaning that the Form shown modally
halts/pauses your application, and has the exclusive focus for all user actions with mouse, or keyboard ... unless you've got some WinAPI stuff going on, like a GlobalHook.
So, what is your goal: under what circumstances do you wish the Form to be moved, hidden, closed ?
If you want the Form to remain open, even if the end-user closes it, you can define an EventHandler for the FormClosing Event, and cancel actually closing it, and hide it:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show(
"Close this Form",
"Confirm Form Close",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2
) == DialogResult.No)
{
this.Hide();
e.Cancel = true;
}
}
This example demonstrates using the FormClosing Event. When the user clicks the ControlBox on Form2, the FormClosing Event fires. A DialogBox appears: if the user just hits 'Enter: it's the same as if the user clicked the "No" Button, and the Form is hidden, and closing it is canceled. If the user clicked the "Yes" Button, then the Form would be closed.