This article describes how to add "window close Tips.
When running the program, you can click the Red Cross in the upper right corner to Close a form. You can also call the Close () method of the form to Close the form. If you want to provide a prompt box before closing the form to prevent important information from being saved, what should you do? Many people will think of adding information box code before calling Close. However, this method is not perfect, because the Close method is called. You do not know where to call the Close method, and you cannot write information box statements everywhere. The correct method is not to call Close, but to call Close."After"
The correct method is to handle the FormClosing event of Form:
Public delegate void FormClosingEventHandler (object sender, FormClosingEventArgs e );
Public event FormClosingEventHandler FormClosing;
After the Form instance is called the Close () method, instead of destroying the Form immediately, the FormClosingEventArgs instance e is created. As a parameter, FormClosing is issued. After the event is processed, check e. whether the value of Cancel is true or not. If the value is true, Cancel the Form destruction. If the value is false, continue to destroy the Form. Therefore, we can assign a value to e. Cancel during processing by processing the FormClosing event, so that we can undo the form and close it. So why do we emphasize "after ". For example, the Code mentioned above can be implemented as follows:
This. FormClosing + = new FormClosingEventHandler (Form1_FormClosing );
Void Form1_FormClosing (object sender, FormClosingEventArgs e)
If (MessageBox. Show (
"Data will be lost when the window is closed! Close the window now ",
MessageBoxIcon. Question )! = DialogResult. OK)
E. Cancel = true;
However, it should be noted that this kind of processing program generally only has code of e. Cancel = true;, and no code of e. Cancel = false. Because events belong to a type of delegation, the delegation is multicast. Therefore, there may be multiple event processing code segments. If a value is assigned, the parameters of the entire delegate may be affected. The requirement here is that once one of the processed code segments e. cancel = true, forms should not be closed, so avoid e. the value assignment statement with Cancel = false affects the processing results of other events.