Как закрыть windows forms

  1. Use the Close() Method to Close Form in C#

  2. Set the DialogResult Property in Windows Forms to Close Form in C#

  3. Use the Application.Exit Method to Exit the Application in C#

  4. Use the Environment.Exit Method to Exit the Application in C#

  5. Use the Form.Hide() Method to Hide Form in C#

  6. Use the Form.Dispose() Method to Dispose Form in C#

  7. Conclusion

How to Close Form in C#

Closing a form is a fundamental operation in C# application development. Whether you’re building a Windows Forms Application or a Windows Presentation Foundation (WPF) Application, understanding how to close a form correctly is crucial for maintaining your application’s integrity and user experience.

This tutorial will explore different methods for closing a form in C# and provide step-by-step explanations and working code examples for each method.

Use the Close() Method to Close Form in C#

The most straightforward way to close a form in C# is by using the Close() method. This method is inherited from the System.Windows.Forms.Form class and is available for Windows Forms and WPF applications.

Inside Form1, we have a button (closeButton) that, when clicked, calls this.Close() to close the form.

using System;
using System.Windows.Forms;

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

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

In the above code, we closed the form in our Windows Forms application that only consists of one form with the Close() method in C#.

This method only closes a single form in our application. It can also close a single form in an application that consists of multiple forms.

Set the DialogResult Property in Windows Forms to Close Form in C#

In Windows Forms applications, you can use the DialogResult property to close a form and indicate a specific result to the caller. This is often used when the form acts as a dialog box or a modal form.

using System;
using System.Windows.Forms;

namespace DialogResultDemo {
  public partial class MainForm : Form {
    public MainForm() {
      InitializeComponent();
    }

    private void okButton_Click(object sender, EventArgs e) {
      this.DialogResult = DialogResult.OK;  // Set the DialogResult
      this.Close();                         // Close the form
    }

    private void cancelButton_Click(object sender, EventArgs e) {
      this.DialogResult = DialogResult.Cancel;  // Set the DialogResult
      this.Close();                             // Close the form
    }
  }

  static class Program {
    [STAThread]
    static void Main() {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      // Show the MainForm as a dialog
      if (new MainForm().ShowDialog() == DialogResult.OK) {
        MessageBox.Show("OK button clicked.");
      } else {
        MessageBox.Show("Cancel button clicked or form closed.");
      }
    }
  }
}

In the above code, we create a Windows Forms application with a form named MainForm containing two buttons (okButton and cancelButton). When the OK or Cancel button is clicked, we set the DialogResult property accordingly and then call this.Close() to close the form.

Use the Application.Exit Method to Exit the Application in C#

The Application.Exit() method is used to close the entire application in C#. This method informs all message loops to terminate execution and closes the application after all the message loops have terminated.

We can also use this method to close a form in a Windows Forms application if our application only consists of one form.

However, use this method with caution. It’s essential to make sure that it’s appropriate to exit the entire application at that point, as it can lead to unexpected behavior if other forms or processes need to be closed or cleaned up.

using System;
using System.Windows.Forms;

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

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

In the above code, when the Exit button is clicked, we call Application.Exit() to exit the entire application.

The drawback with this method is that the Application.Exit() method exits the whole application. So, if the application contains more than one form, all the forms will be closed.

Use the Environment.Exit Method to Exit the Application in C#

While it’s possible to close an application by calling Environment.Exit(0), it is generally discouraged.

This method forcefully terminates the application without allowing it to clean up resources or execute finalizers. It should only be used as a last resort when dealing with unhandled exceptions or critical issues.

using System;
using System.Windows.Forms;

namespace EnvironmentExitDemo {
  public partial class MainForm : Form {
    public MainForm() {
      InitializeComponent();
    }

    private void exitButton_Click(object sender, EventArgs e) {
      Environment.Exit(0);  // Forcefully exit the entire application
    }
  }
}

In the above code, when the Exit button is clicked, we call Environment.Exit(0) to forcefully exit the entire application. This should be used sparingly, as it does not allow proper cleanup.

Application.Exit() is specific to Windows Forms applications and provides a controlled, graceful exit, while Environment.Exit() is a general-purpose method that forcibly terminates the application without any cleanup or event handling.

Use the Form.Hide() Method to Hide Form in C#

Sometimes, you want to hide the form instead of closing it; you can use the Form.Hide() method to do this. The form remains in memory and can be shown again using this.Show() or this.Visible = true;.

using System;
using System.Windows.Forms;

namespace FormHideDemo {
  public partial class MainForm : Form {
    public MainForm() {
      InitializeComponent();
    }

    private void hideButton_Click(object sender, EventArgs e) {
      this.Hide();  // Hide the form
    }

    private void showButton_Click(object sender, EventArgs e) {
      this.Show();  // Show the hidden form
    }
  }
}

In the above code, we create a Windows Forms application with a form named MainForm containing two buttons (hideButton and showButton).

When clicking the Hide button, we call this.Hide() to hide the form. When clicking the Show button, we call this.Show() to show the hidden form.

Use the Form.Dispose() Method to Dispose Form in C#

You can explicitly dispose of a form and release its resources using the Form.Dispose() method. It should be used when you explicitly want to release resources associated with the form, but it does not close its window.

using System;
using System.Windows.Forms;

namespace FormDisposeDemo {
  public partial class MainForm : Form {
    public MainForm() {
      InitializeComponent();
    }

    private void disposeButton_Click(object sender, EventArgs e) {
      this.Dispose();  // Dispose of the form
    }
  }
}

In the above code, when clicking the Dispose button, we call this.Dispose() to explicitly dispose of the form. This should be used when you want to release resources associated with the form.

Conclusion

Closing a form in C# involves several methods and considerations, depending on your application’s requirements. We have explored various methods, including using the Close() method, setting the DialogResult property, exiting the application, hiding the form, and disposing of the form.

Choosing the right method depends on your specific use case. Understanding when and how to use each method is crucial to ensure your application behaves as expected and provides a seamless user experience.

By mastering form closure techniques in C#, you can develop robust and user-friendly applications that meet the needs of your users while maintaining code integrity and resource management.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Конвейеры ETL с Apache Airflow и Python

AI_Generated 13.05.2025

ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .

Выполнение асинхронных задач в Python с asyncio

py-thonny 12.05.2025

Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .

Работа с gRPC сервисами на C#

UnmanagedCoder 12.05.2025

gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .

CQRS (Command Query Responsibility Segregation) на Java

Javaican 12.05.2025

CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .

Шаблоны и приёмы реализации DDD на C#

stackOverflow 12.05.2025

Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .

Исследование рантаймов контейнеров Docker, containerd и rkt

Mr. Docker 11.05.2025

Когда мы говорим о контейнерных рантаймах, мы обсуждаем программные компоненты, отвечающие за исполнение контейнеризованных приложений. Это тот слой, который берет образ контейнера и превращает его в. . .

Micronaut и GraalVM — будущее микросервисов на Java?

Javaican 11.05.2025

Облачные вычисления безжалостно обнажили ахиллесову пяту Java — прожорливость к ресурсам и медлительный старт приложений. Традиционные фреймворки, годами радовавшие корпоративных разработчиков своей. . .

Здравствуйте.
Имеется приложение c# winforms. Весь нужный код выполняется функциями еще до загрузки самой формы (по идее), выглядит так:

public Form1()
{
            this.Opacity = 0;
            this.ShowInTaskbar = false;
            this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
            doit();
}

Собственно, в ф-ции doit мне нужно закрыть данное приложение. Из-за того, что форма грузиться не должна (я даже удалил Form1_Load из кода), адекватно варианты закрытия не работают (что только не перепробовал). Все время вылетает «Приложение *appname* завершило работу».
Нужен вариант, как я могу завершить приложение из той самой ф-ции, без открытия окна завершения.


  • Вопрос задан

  • 2570 просмотров

Пригласить эксперта

Удалите весь код, связанный с формой. Сделайте метод инициализации статическим. В настройках проекта укажите тип «консольное приложение», а точкой входа метод инициализации.

Если при Application.Exit идёт вылет, то посмотрите на событие FormClosing. Видимо в нём что-то делается, а вообще запустите в дебаг режиме и покажите полностью ошибку.

PS: В качестве костыля можете использовать Environment.Exit(0);

public Form1()
        {
            InitializeComponent();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }

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

        private void button2_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

Войдите, чтобы написать ответ


  • Показать ещё
    Загружается…

Минуточку внимания

There is a common and simple requirement in windows applications to Open a new form(say Form2) when clicked a button in Form1 and also close Form1 at the same time.

Table of Contents

  • On Button Click Open Form 2 and Close Form 1
    • 1)  Close Form1 and Show Form2 – C#
    • 2)  Use Application.Run for each form in Main() method
    • 3) Hide Form1 and Show Form2 – C#
  • Summary

On Button Click Open Form 2 and Close Form 1

There are many ways you can close current form and open a new form in .NET.See below,

1)  Close Form1 and Show Form2 – C#

private void btnLogin_Click(object sender, EventArgs e)
{
     this.Close(); //Close Form1,the current open form.

     Form2 frm2 = new Form2();

     frm2.Show(); // Launch Form2,the new form.
}

2)  Use Application.Run for each form in Main() method

//Declare a boolean property.This property to be set as true on button click.

public bool IsLoggedIn { get; set; }

private void btnLogin_Click(object sender, EventArgs e)
{
    this.Close(); //Close Form1

    /* Set the property to true while closing Form1.This propert will be checked 
       before running Form2 in Main method.*/
    IsLoggedIN = true;
}

Then Update the Main() method as below.

[STAThread]
static void Main()
{
     Application.EnableVisualStyles();

     Application.SetCompatibleTextRenderingDefault(false);

     Form1 frm1 = new Form1();

     Application.Run(frm1);

    /*Here the property IsLoggedIn is used to ensure that Form2 won't be shown when user closes Form1 using X                 button or a Cancel  button inside Form1.*/
    if (frm1.IsLoggedIn)
    {
       Application.Run(new Form2());
    }

}

3) Hide Form1 and Show Form2 – C#

Here Form1 will remain open as long as the application is live.This option is the worst and hence not at all suggested.

private void btnLogin_Click(object sender, EventArgs e)
{
   this.Hide(); //Hide Form1.

   Form2 frm2 = new Form2();

   frm2.Show(); // Launch Form2
}

Summary

In this post we have seen samples to close Form1 and open Form2 in C# and same code logic can be used in VB.NET. Hope these code snippets has helped you to rectify the issues during close one form and open another form in C# or VB.NET. Leave your comments in the comment section below.

Related Items : 
Close one form and Open another form On Button click,
Open new Form but Closing current Form,
vb.net close form from another form,
How to close form1 and open form2 in VB.NET,
Application.run to close a form and open another form

Reader Interactions

Trackbacks

Closing a form in C# is a common task in Windows Forms applications. There are several ways to achieve this, depending on your specific requirements. In this blog post, we will explore different methods to close the current form in C#.

Using the Close Method

The simplest way to close the current form is by calling the Close method. This method closes the form and releases all resources associated with it.

this.Close();

Using Application.Exit

Another approach is to use Application.Exit(), which exits the application and closes all open forms.

Application.Exit();

Handling the FormClosing Event

You can also handle the FormClosing event to perform custom actions before closing the form. In this event handler, you can cancel the form closing operation or execute additional logic.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Add custom logic here
}

Using DialogResult

If your form was opened using ShowDialog, you can set the DialogResult property to indicate how the form should be closed.

this.DialogResult = DialogResult.OK;

Summary

Closing a form in C# is an essential part of developing Windows Forms applications. By using the methods mentioned above, you can effectively close the current form based on your requirements.

Remember to choose the method that best fits your scenario and always consider any additional cleanup or validation that may be needed before closing the form.

Now that you have learned various ways to close the current form in C#, you can implement them in your projects with ease. Happy coding!

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как подключить беспроводные наушники к ноутбуку windows 7 домашняя базовая
  • Cloud backup windows 10
  • Активатор windows 10 овгорский
  • Как создать загрузочную флешку windows 10 с официального сайта microsoft windows
  • Windows 10 не заходит в учетную запись пользователя