问题
Programming in C#.NET 4.0 is my latest passion, and I would like to know how to add functionality to the standard Windows.Forms Exit button (the red X in the upper right corner of the form).
I have found a way to disable the button, but since I think it compromises the user experiance, I would like to hook up some functionalities instead.
How to disable exit button:
#region items to disable quit-button
const int MF_BYPOSITION = 0x400;
[DllImport("User32")]
private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("User32")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("User32")]
private static extern int GetMenuItemCount(IntPtr hWnd);
#endregion
...
private void DatabaseEditor_Load(object sender, EventArgs e)
{
this.graphTableAdapter.Fill(this.diagramDBDataSet.Graph);
this.intervalTableAdapter.Fill(this.diagramDBDataSet.Interval);
// Disable quit-button on load
IntPtr hMenu = GetSystemMenu(this.Handle, false);
int menuItemCount = GetMenuItemCount(hMenu);
RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
}
But how on earth do I attach a method, before the application exits with the standard exit-button. I would like to XmlSerialize a List before exiting the windows form.
回答1:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(MessageBox.Show("Are you sure you want to exit?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
}
回答2:
If you want to write codes before form closed, use FormClosing event
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
回答3:
The best way that I found is actually to create an EventHandler that will call the method that you want to be called.
In the constructor :
this.Closed += new EventHandler(theWindow_Closed);
Then you create the method :
private void theWindow_Closed(object sender, System.EventArgs e)
{
//do the closing stuff
}
来源:https://stackoverflow.com/questions/3163885/add-functionality-to-windows-forms-exit-button