Close Form in C#

  1. Close Form With the Application.Exit() Function in C
  2. Close Form With the Form.Close() Function in C

This tutorial will introduce the methods to close a form in C#.

Close Form With the Application.Exit() Function in C

The Application.Exit() function is used to close the entire application in C#. The Application.Exit() function informs all message loops to terminate execution and closes the application after all the message loops have terminated. We can also use the Application.Exit() function to close a form in a Windows Form application if our application only consists of one form. See the following example.

using System;
using System.Windows.Forms;

namespace close_form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

In the above code, we closed the form in our Windows Form application that only consists of one form with the Application.Exit() function in C#. The only drawback with this approach is that the Application.Exit() function exits the whole application. So, if the application contains more than one form, all the forms will be closed.

Close Form With the Form.Close() Function in C

The Form.Close() function is used to close a Form in a Windows Form application in C#. We can use the Form.Close() function inside the button click event to close the specified form by clicking a button. See the following example.

using System;
using System.Windows.Forms;

namespace close_form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

In the above code, we closed the form in our Windows Form application that only consists of one form with the Form.Close() function in C#. Unlike the previous method, this method only closes a single Form in our application. This method can be used to close a single form in an application that consists of multiple forms.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp GUI

  • Multiline Label in C#
  • Clear ListBox in C#