Any time you use 'MessageBox.Show the modal dialog box put up by WinForms has exclusive focus, and it is closed (and disposed) when the user clicks one of its Buttons. When the MessageBox Dialog is closed, Application Focus should return to the last Window/Control that had Focus before the MessageBox was shown.
If you want to get the MessageBox that enables cancelling closing the Application to show when user chooses 'Close Window' in the TaskBar, here's an example; in this example, if the Main Form is minimized when the 'Close is canceled, then I reset the WindowState to 'Normal, and bring the Main Form to the front of the z-order and invoke Focus on it:
using System.Windows.Forms;
namespace YourNameSapce
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if
(
MessageBox.Show("Exit the Application ?",
"Exit ?",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1)
== DialogResult.Cancel
)
{
e.Cancel = true;
if (this.WindowState == FormWindowState.Minimized)
{
this.WindowState = FormWindowState.Normal;
}
this.BringToFront();
this.Focus();
}
}
}
}