C# Windows Form: On Close Do [Process]

前端 未结 6 1989
我在风中等你
我在风中等你 2021-01-03 20:19

How can I get my windows form to do something when it is closed.

相关标签:
6条回答
  • 2021-01-03 20:42
     public FormName()
     {
          InitializeComponent();
          this.FormClosed += FormName_FormClosed;
     }
    
    private void FormName_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
    {
       //close logic here
    }
    
    0 讨论(0)
  • 2021-01-03 20:44

    Add an Event Handler to the FormClosed event for your Form.

    public class Form1
    {
    
        public Form1()
        {    
            this.FormClosed += MyClosedHandler;
        }
    
        protected void MyClosedHandler(object sender, EventArgs e)
        {
            // Handle the Event here.
        }
    }
    
    0 讨论(0)
  • 2021-01-03 20:46

    Or another alternative is to override the OnFormClosed() or OnFormClosing() methods from System.Windows.Forms.Form.

    Whether you should use this method depends on the context of the problem, and is more usable when the form will be sub classed several times and they all need to perform the same code.

    Events are more useful for one or two instances if you're doing the same thing.

    public class FormClass : Form
    {
       protected override void OnFormClosing(FormClosingEventArgs e)
       {
            base.OnFormClosing(e);
            // Code
       } 
    }
    
    0 讨论(0)
  • 2021-01-03 20:56

    Handle the FormClosed event.

    To do that, go to the Events tab in the Properties window and double-click the FormClosed event to add a handler for it.

    You can then put your code in the generated MyForm_FormClosed handler.

    You can also so this by overriding the OnFormClosed method; to do that, type override onformcl in the code window and OnFormClosed from IntelliSense.

    If you want to be able to prevent the form from closing, handle the FormClosing event instead, and set e.Cancel to true.

    0 讨论(0)
  • 2021-01-03 20:56

    WinForms has two events that you may want to look at.

    The first, the FormClosing event, happens before the form is actually closed. In this event, you can still access any controls and variables in the form's class. You can also cancel the form close by setting e.Cancel = true; (where e is a System.Windows.Forms.FormClosingEventArgs sent as the second argument to FormClosing).

    The second, the FormClosed event, happens after the form is closed. At this point, you can't access any controls that the form had, although you can still do cleanup on variables (such as Closing managed resources).

    0 讨论(0)
  • 2021-01-03 21:03

    Syntax :

       form_name.ActiveForm.Close();
    

    Example:

       {
             Form1.ActiveForm.close();
       }
    
    0 讨论(0)
提交回复
热议问题