Close Form in C#

Close Form in C#

Muhammad Maisam Abbas Apr-06, 2021 Mar-28, 2021 Csharp Csharp GUI
  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.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp GUI

  • Save File Dialog in C#
  • Group the Radio Buttons in C#
  • Add Right Click Menu to an Item in C#
  • Add Items in C# ComboBox
  • Add Placeholder to a Textbox in C#
  • Simulate a Key Press in C#