Form Closing Event Args Класс
Определение
Предоставляет данные для события FormClosing. Provides data for the FormClosing event.
Примеры
Комментарии
Это FormClosing событие происходит непосредственно перед закрытием формы пользователем, через пользовательский интерфейс или программным путем посредством вызова методов, таких как Close в Form классе или Exit в Application классе. The FormClosing event occurs just before a form is closed, either by the user, through the user interface (UI), or programmatically, through calls to methods such as Close in the Form class, or Exit in the Application class.
Если форма содержит дочерние или собственные формы, FormClosing для каждого из них также создается событие. If a form has any child or owned forms, a FormClosing event is also raised for each one. Если одна из форм отменяет событие, ни одна из форм не закрыта. If any one of the forms cancels the event, none of the forms are closed. Поэтому соответствующие FormClosed события не отправляются ни в одну из форм. Therefore the corresponding FormClosed events are not sent to any of the forms.
FormClosingEventArgsКласс предоставляет данные для этого события. The FormClosingEventArgs class provides data for this event. Два важных члена — это Cancel CloseReason Свойства и. Two important members are the Cancel and CloseReason properties. Это событие можно отменить, задав Cancel свойству значение true. The event can be canceled by setting the Cancel property to true. CloseReasonСвойство содержит причину, по которой форма закрывается. The CloseReason property provides a reason why the form is being closed.
Конструкторы
Инициализирует новый экземпляр класса FormClosingEventArgs. Initializes a new instance of the FormClosingEventArgs class.
Свойства
Возвращает или задает значение, показывающее, следует ли отменить событие. Gets or sets a value indicating whether the event should be canceled.
Получает значение, указывающее, почему форма закрывается. Gets a value that indicates why the form is being closed.
Методы
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
Служит хэш-функцией по умолчанию. Serves as the default hash function.
Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.
Источник
Порядок событий в формах Windows Forms Order of Events in Windows Forms
Особый интерес для разработчиков представляет порядок, в котором вызываются события в приложениях Windows Forms, для обеспечения обработки каждого из этих событий в свою очередь. The order in which events are raised in Windows Forms applications is of particular interest to developers concerned with handling each of these events in turn. Если ситуация требует аккуратной обработки событий, например когда производится перерисовка части формы, то необходимо знать точный порядок, в котором вызываются события во время выполнения. When a situation calls for meticulous handling of events, such as when you are redrawing parts of the form, an awareness of the precise order in which events are raised at run time is necessary. В этом разделе приведены некоторые сведения о порядке событий, возникающих на нескольких важных этапах жизненного цикла приложений и элементов управления. This topic provides some details on the order of events during several important stages in the lifetime of applications and controls. Конкретные сведения о порядке событий ввода мыши см. в разделе события мыши в Windows Forms. For specific details about the order of mouse input events, see Mouse Events in Windows Forms. Общие сведения о событиях в Windows Forms см. в разделе Общие сведения о событиях. For an overview of events in Windows Forms, see Events Overview. Дополнительные сведения о описывающего обработчиков событий см. в разделе Общие сведения об обработчиках событий. For details about the makeup of event handlers, see Event Handlers Overview.
События запуска и завершения работы приложения Application Startup and Shutdown Events
Классы Form и Control предоставляют набор событий, связанных с запуском и завершением приложения. The Form and Control classes expose a set of events related to application startup and shutdown. При запуске приложения Windows Forms события запуска главной формы вызываются в следующем порядке: When a Windows Forms application starts, the startup events of the main form are raised in the following order:
При закрытии приложения события запуска главной формы вызываются в следующем порядке: When an application closes, the shutdown events of the main form are raised in the following order:
Событие ApplicationExit класса Application вызывается после событий завершения работы основной формы. The ApplicationExit event of the Application class is raised after the shutdown events of the main form.
В Visual Basic 2005 содержатся дополнительные события приложений, такие как WindowsFormsApplicationBase.Startup и WindowsFormsApplicationBase.Shutdown. Visual Basic 2005 includes additional application events, such as WindowsFormsApplicationBase.Startup and WindowsFormsApplicationBase.Shutdown.
События, связанные с фокусом и проверками Focus and Validation Events
При изменении фокуса с помощью клавиатуры (при нажатии клавиш TAB, SHIFT+TAB и так далее), путем вызова методов Select или SelectNextControl, либо присвоением свойства ActiveControl текущей форме, события фокуса ввода класса Control происходят в следующем порядке: When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ActiveControl property to the current form, focus events of the Control class occur in the following order:
При изменении фокуса ввода с помощью мыши или путем вызова метода Focus события фокуса класса Control происходят в следующем порядке. When you change the focus by using the mouse or by calling the Focus method, focus events of the Control class occur in the following order:
Источник
Событие — это действие, требующее реагирования или «обработки» в коде. An event is an action that you can respond to, or «handle,» in code. События могут генерироваться действиями пользователя (например, нажатием кнопки мыши или клавиши на клавиатуре), программным кодом или системой. Events can be generated by a user action, such as clicking the mouse or pressing a key, by program code, or by the system.
Приложения, управляемые событиями, выполняют код в ответ на событие. Event-driven applications execute code in response to an event. Каждая форма и элемент управления имеют предопределенный набор событий, который можно запрограммировать. Each form and control exposes a predefined set of events that you can program against. Если возникает такое событие, а в соответствующем обработчике событий имеется код, этот код выполняется. If one of these events occurs and there’s code an associated event handler, that code is invoked.
Типы порождаемых объектом событий могут варьироваться, но многие их них стандартны для большинства элементов управления. The types of events raised by an object vary, but many types are common to most controls. Например, большинство объектов обработают событие Click. For example, most objects will handle a Click event. Если пользователь откроет форму, в форме сработает код обработчика события Click. If a user clicks a form, code in the form’s Click event handler is executed.
Многие события возникают вместе с другими событиями. Many events occur in conjunction with other events. Например, при возникновении события DoubleClick возникают также события MouseDown, MouseUp и Click. For example, in the course of the DoubleClick event occurring, the MouseDown, MouseUp, and Click events occur.
Сведения о получении и использовании события см. в разделе Обработка и вызов событий. For information about how to raise and consume an event, see Handling and raising events.
Делегаты и их роли Delegates and their role
В данной модели событий делегаты служат для связки событий с методами, которые используются для их обработки. This event model uses delegates to bind events to the methods that are used to handle them. Делегаты позволяют другим классам записывать уведомление о событии, определяя метод обработки. The delegate enables other classes to register for event notification by specifying a handler method. При возникновении события делегат вызывает соответствующий метод. When the event occurs, the delegate calls the bound method. Сведения об определении делегатов см. в разделе Обработка и вызов событий. For more information about how to define delegates, see Handling and raising events.
Делегаты можно связать с одним или несколькими методами, создав так называемую многоадресную рассылку. Delegates can be bound to a single method or to multiple methods, referred to as multicasting. При создании делегата для события вы обычно создаете событие многоадресной рассылки. When creating a delegate for an event, you typically create a multicast event. Редким исключением является событие, вызывающее выполнение определенной процедуры (например, отображение диалогового окна), которая не будет логически повторяться несколько раз за событие. A rare exception might be an event that results in a specific procedure (such as displaying a dialog box) that wouldn’t logically repeat multiple times per event. Сведения о том, как создать многоадресный делегат, см. в практическом руководстве Объединение делегатов (многоадресные делегаты). For information about how to create a multicast delegate, see How to combine delegates (Multicast Delegates).
Делегат многоадресной рассылки поддерживает список вызова методов, к которым он привязан. A multicast delegate maintains an invocation list of the methods it’s bound to. Делегат многоадресной рассылки поддерживает метод Combine, позволяющий добавить метод в список вызова, и метод Remove, позволяющий его удалить. The multicast delegate supports a Combine method to add a method to the invocation list and a Remove method to remove it.
Когда приложение регистрирует событие, элемент управления порождает это событие, вызывая для него делегат. When an event is recorded by the application, the control raises the event by invoking the delegate for that event. Делегат, в свою очередь, вызывает соответствующий метод. The delegate in turn calls the bound method. В самом распространенном случае (делегат многоадресной рассылки) делегат вызывает каждый метод связки из списка вызова по очереди, что обеспечивает уведомление «один ко многим». In the most common case (a multicast delegate), the delegate calls each bound method in the invocation list in turn, which provides a one-to-many notification. Данная стратегия означает, что элементу управления не нужно вести список целевых объектов для уведомления о событии, поскольку записью и уведомлением занимается делегат. This strategy means that the control doesn’t need to maintain a list of target objects for event notification—the delegate handles all registration and notification.
Делегаты также позволяют связать с одним методом несколько событий, чтобы использовать уведомление по типу многие-к-одному. Delegates also enable multiple events to be bound to the same method, allowing a many-to-one notification. Например, событие нажатия на кнопку и событие выбора команды в меню вызывают один и тот же делегат, который вызывает один и тот же метод, обрабатывающий эти события одинаковым образом. For example, a button-click event and a menu-command–click event can both invoke the same delegate, which then calls a single method to handle these separate events the same way.
В делегатах используется динамический механизм связки: во время выполнения делегат может быть связан с любым методом, подпись которого совпадает с подписью обработчика событий. The binding mechanism used with delegates is dynamic: a delegate can be bound at run-time to any method whose signature matches that of the event handler. С помощью этой функции можно устанавливать или изменять метод связки в зависимости от условий и динамически привязывать обработчик событий к элементу управления. With this feature, you can set up or change the bound method depending on a condition and to dynamically attach an event handler to a control.
Источник
Escape button to close Windows Forms form in C#
I have tried the following:
But it doesn’t work.
And still nothing’s working.
The KeyPreview on my Windows Forms form properties is set to true. What am I doing wrong?
8 Answers 8
You should just be able to set the Form’s CancelButton property to your Cancel button and then you won’t need any code.
Assuming that you have a «Cancel» button, setting the form’s CancelButton property (either in the designer or in code) should take care of this automatically. Just place the code to close in the Click event of the button.
The accepted answer indeed is correct, and I’ve used that approach several times. Suddenly, it would not work anymore, so I found it strange. Mostly because my breakpoint would not be hit for ESC key, but it would hit for other keys.
After debugging I found out that one of the controls from my form was overriding ProcessCmdKey method, with this code:
. and this was preventing my form from getting the ESC key (notice the return true ). So make sure that no child controls are taking over your input.
You set KeyPreview to true in your form options and then you add the Keypress event to it. In your keypress event you type the following:
key.Char == 27 is the value of escape in ASCII code.
You need add this to event «KeyUp».
You can also Trigger some other form.
E.g. trigger a Cancel-Button if you edit the Form CancelButton property and set the button Cancel.
In the code you treath the Cancel Button as follows to close the form:
By Escape button do you mean the Escape key? Judging by your code I think that’s what you want. You could also try Application.Exit(), but Close should work. Do you have a worker thread? If a non-background thread is running this could keep the application open.
Not the answer you’re looking for? Browse other questions tagged c# winforms or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.27.39167
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Hide form instead of closing when close button clicked
When a user clicks the X button on a form, how can I hide it instead of closing it?
I have tried this.hide() in FormClosing but it still closes the form.
7 Answers 7
I’ve commented in a previous answer but thought I’d provide my own. Based on your question this code is similar to the top answer but adds the feature another mentions:
So cancel then hide.
If you want to use the show/hide method I’ve actually done this myself for a menu structure a game I’ve recently done. This is how I did it:
Create yourself a button and for what you’d like to do, for example a ‘Next’ button and match the following code to your program. For a next button in this example the code would be:
Here is a snippet of the code I used in my game to help you understand what I’m trying to explain:
So there is a show/hide method few lines of code, rather than doing a massive piece of code for such a simple task. I hope this helps to solve your problem.
Note that when doing this (several answers have been posted) that you also need to find a way to ALLOW the user to close the form when they really want to. This really becomes a problem if the user tries to shut down the machine when the application is running, because (at least on some OS) this will stop the OS from shutting down properly or efficiently.
This is the behavior of Modal forms. When you use form.ShowDialog() you are asking for this behavior. The reason for this is that form.ShowDialog doesn’t return until the form is hidden or destroyed. So when the form is hidden, the pump inside form.ShowDialog destroys it so that it can return.
If you want to show and hide a form, then you should be using the Modeless dialog model http://msdn.microsoft.com/en-us/library/39wcs2dh(VS.80).aspx
form.Show() returns immediately, you can show and hide this window all you want and it will not be destroyed until you explicitly destroy it.
When you use modeless forms that are not children of a modal form, then you also need to run a message pump using Application.Run or Application.DoEvents in a loop. If the thread that creates a form exits, then the form will be destroyed. If that thread doesn’t run a pump then the forms it owns will be unresponsive.
Edit: this sounds like the sort of thing that the ApplicationContext is designed to solve. http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx
Basically, you derive a class from ApplicationContext, pass an instance of your ApplicationContext as an argument to Application.Run()
Your application context will need to know when it’s ok to exit the application and when having the form(s) hidden should not exit the application. When it’s time for the app to exit. Your application context or form can call the application context’s ExitThread() method to terminate the message loop. At that point Application.Run() will return.
Without knowing more about the heirarchy of your forms and your rules for deciding when to hide forms and when to exit, it’s impossible to be more specific.
Источник
ASPxClientPopupWindowCancelEventArgs.closeReason Property
Gets the value that identifies the reason the popup window is about to close.
Declaration
closeReason: ASPxClientPopupControlCloseReason
Property Value
Type | Description |
---|---|
ASPxClientPopupControlCloseReason |
One of the ASPxClientPopupControlCloseReason enumeration values. |
See Also
Основные свойства форм
Последнее обновление: 31.10.2015
С помощью специального окна Properties (Свойства) справа Visual Studio предоставляет нам удобный интерфейс для управления свойствами элемента:
Большинство этих свойств оказывает влияние на визуальное отображение формы. Пробежимся по основным свойствам:
-
Name: устанавливает имя формы — точнее имя класса, который наследуется от класса
Form
-
BackColor: указывает на фоновый цвет формы. Щелкнув на это свойство, мы сможем выбрать тот цвет, который нам подходит
из списка предложенных цветов или цветовой палитры -
BackgroundImage: указывает на фоновое изображение формы
-
BackgroundImageLayout: определяет, как изображение, заданное в свойстве BackgroundImage, будет располагаться на форме.
-
ControlBox: указывает, отображается ли меню формы. В данном случае под меню понимается меню самого верхнего уровня, где
находятся иконка приложения, заголовок формы, а также кнопки минимизации формы и крестик. Если данное свойство имеет значение false, то мы не увидим
ни иконку, ни крестика, с помощью которого обычно закрывается форма -
Cursor: определяет тип курсора, который используется на форме
-
Enabled: если данное свойство имеет значение false, то она не сможет получать ввод от пользователя, то есть мы не сможем
нажать на кнопки, ввести текст в текстовые поля и т.д. -
Font: задает шрифт для всей формы и всех помещенных на нее элементов управления. Однако, задав у элементов формы свой шрифт,
мы можем тем самым переопределить его -
ForeColor: цвет шрифта на форме
-
FormBorderStyle: указывает, как будет отображаться граница формы и строка заголовка. Устанавливая данное свойство в None
можно создавать внешний вид приложения произвольной формы -
HelpButton: указывает, отображается ли кнопка справки формы
-
Icon: задает иконку формы
-
Location: определяет положение по отношению к верхнему левому углу экрана, если для свойства
StartPosition
установлено значениеManual
-
MaximizeBox: указывает, будет ли доступна кнопка максимизации окна в заголовке формы
-
MinimizeBox: указывает, будет ли доступна кнопка минимизации окна
-
MaximumSize: задает максимальный размер формы
-
MinimumSize: задает минимальный размер формы
-
Opacity: задает прозрачность формы
-
Size: определяет начальный размер формы
-
StartPosition: указывает на начальную позицию, с которой форма появляется на экране
-
Text: определяет заголовок формы
-
TopMost: если данное свойство имеет значение
true
, то форма всегда будет находиться поверх других окон -
Visible: видима ли форма, если мы хотим скрыть форму от пользователя, то можем задать данному свойству значение
false
-
WindowState: указывает, в каком состоянии форма будет находиться при запуске: в нормальном, максимизированном или минимизированном
Программная настройка свойств
С помощью значений свойств в окне Свойства мы можем изменить по своему усмотрению внешний вид формы, но все то же самое мы можем сделать
динамически в коде. Перейдем к коду, для этого нажмем правой кнопкой мыши на форме и выберем в появившемся контекстном меню View Code (Просмотр кода). Перед нами открывается файл кода
Form1.cs. Изменим его следующим образом:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HelloApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); Text = "Hello World!"; this.BackColor = Color.Aquamarine; this.Width = 250; this.Height = 250; } } }
В данном случае мы настроили несколько свойств отображения формы: заголовок, фоновый цвет, ширину и высоту.
При использовании конструктора формы надо учитывать, что весь остальной код должен идти после вызова метода InitializeComponent()
, поэтому все установки свойств
здесь расположены после этого метода.
Установка размеров формы
Для установки размеров формы можно использовать такие свойства как Width/Height или Size. Width/Height принимают числовые значения, как в вышеприведенном
примере. При установке размеров через свойство Size, нам надо присвоить свойству объект типа Size:
this.Size = new Size(200,150);
Объект Size в свою очередь принимает в конструкторе числовые значения для установки ширины и высоты.
Начальное расположение формы
Начальное расположение формы устанавливается с помощью свойства StartPosition
, которое может принимать одно из следующих значений:
-
Manual: Положение формы определяется свойством Location
-
CenterScreen: Положение формы в центре экрана
-
WindowsDefaultLocation: Позиция формы на экране задается системой Windows, а размер определяется свойством Size
-
WindowsDefaultBounds: Начальная позиция и размер формы на экране задается системой Windows
-
CenterParent: Положение формы устанавливается в центре родительского окна
Все эти значения содержатся в перечислении FormStartPosition
, поэтому, чтобы, например, установить форму в центре экрана, нам надо прописать
так:
this.StartPosition = FormStartPosition.CenterScreen;
Фон и цвета формы
Чтобы установить цвет как фона формы, так и шрифта, нам надо использовать цветовое значение, хранящееся в структуре Color:
this.BackColor = Color.Aquamarine; this.ForeColor = Color.Red;
Кроме того, мы можем в качестве фона задать изображение в свойстве BackgroundImage
, выбрав его в окне свойств или в коде, указав путь к изображению:
this.BackgroundImage = Image.FromFile("C:\\Users\\Eugene\\Pictures\\3332.jpg");
Чтобы должным образом настроить нужное нам отображение фоновой картинки, надо использовать свойство BackgroundImageLayout
,
которое может принимать одно из следующих значений:
-
None: Изображение помещается в верхнем левом углу формы и сохраняет свои первоначальные значения
-
Tile: Изображение располагается на форме в виде мозаики
-
Center: Изображение располагается по центру формы
-
Stretch: Изображение растягивается до размеров формы без сохранения пропорций
-
Zoom: Изображение растягивается до размеров формы с сохранением пропорций
Например, расположим форму по центру экрана:
this.StartPosition = FormStartPosition.CenterScreen;
-
Use the
Close()
Method to Close Form in C# -
Set the
DialogResult
Property in Windows Forms to Close Form in C# -
Use the
Application.Exit
Method to Exit the Application in C# -
Use the
Environment.Exit
Method to Exit the Application in C# -
Use the
Form.Hide()
Method to Hide Form in C# -
Use the
Form.Dispose()
Method to Dispose Form in C# -
Conclusion
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
public PrintService() { InitializeComponent(); this.WindowState = FormWindowState.Minimized; } private void PrintService_Load(object sender, EventArgs e) { //Initialization is not visible //notifyIcon.Visible = false; } protected override void OnClosing(CancelEventArgs e) { if (MessageBox.Show("Are you sure to turn off the printing service?", "Exit confirmation", MessageBoxButtons.OKCancel) != DialogResult.OK) { e.Cancel = true; } base.OnClosing(e); }
Message prompt optimization
* Reference: http://www.cnblogs.com/ManchesterUnitedFootballClub/p/4596465.html Winfrom prompt message box public class
* http://www.cnblogs.com/wuhuacong/archive/2011/11/22/2259128.html Dialog style assimilation of Winform development framework
http://www.aichengxu.com/other/1850478.htm DevExpress MessageBox pop-up box Low-level class
Front desk call: //Figure 1 the foreground call MessageBox.Show("test", "title", MessageBoxButtons.OK); //Figure 2 the foreground call Functionjsj.ShowMsg("test", Functionjsj.MsgType.OK); Description: Functionjsj is a custom class: there are three types of output: Functionjsj.ShowMsg (message, enumeration type); Functionjsj.ShowMsg (message, title, enumeration type); Functionjsj.ShowMsgBox (message, title, enumeration type); Low-level class: #region DevExpress MessageBox pop-up box #region Enumerate popup types public enum MsgType { /// <summary> /// Hint /// </summary> OK = 0, /// <summary> /// caveat /// </summary> Warning = 1, /// <summary> /// Inquire /// </summary> Question = 2, /// <summary> /// Error /// </summary> Exception = 3, /// <summary> /// Yes/no/cancel /// </summary> YesNoCancel = 4, /// <summary> /// Yes/no /// </summary> YesNo = 5 } #endregion /// <summary> /// Show message /// </summary> /// <param name="msg">news</param> /// <param name="ie">Message type</param> /// <returns>When the user needs to make a choice, return YES or NO, otherwise return, ok, cancel, etc.</returns> public static System.Windows.Forms.DialogResult ShowMsg(string msg, MsgType msgType) { switch (msgType) { case MsgType.OK: return ShowMsg(msg, "information", MsgType.OK); case MsgType.Question: return ShowMsg(msg, "confirm", MsgType.Question); case MsgType.Warning: return ShowMsg(msg, "caveat", MsgType.Warning); case MsgType.Exception: Exception(msg); return System.Windows.Forms.DialogResult.OK; case MsgType.YesNoCancel: return ShowMsg(msg, "please choose", MsgType.YesNoCancel); case MsgType.YesNo: return ShowMsg(msg, "please choose", MsgType.YesNo); default: return System.Windows.Forms.DialogResult.Cancel; } } /// <summary> /// Show message /// </summary> /// <param name="msg">news</param> /// <param name="caption">Title The system will automatically add some information</param> /// <param name="msgType">Message type</param> /// <returns>When the user needs to make a choice, return YES or NO, otherwise return, ok, cancel, etc.</returns> public static System.Windows.Forms.DialogResult ShowMsg(string msg, string caption, MsgType msgType) { switch (msgType) { case MsgType.OK: return ShowMsgBox(msg, caption, msgType); case MsgType.Question: return ShowMsgBox(msg, caption, msgType); case MsgType.Warning: return ShowMsgBox(msg, caption, msgType); case MsgType.Exception: Exception(msg); return System.Windows.Forms.DialogResult.OK; case MsgType.YesNoCancel: return ShowMsgBox(msg, caption, msgType); case MsgType.YesNo: return ShowMsgBox(msg, caption, msgType); default: return System.Windows.Forms.DialogResult.Cancel; } } /// <summary> /// Show message /// </summary> /// <param name="msg">news</param> /// <param name="catpion">title</param> /// <param name="msgType">Message type</param> /// <returns>When the user needs to make a choice, return YES or NO, otherwise return, ok, cancel, etc.</returns> public static System.Windows.Forms.DialogResult ShowMsgBox(string msg, string catpion, MsgType msgType) { switch (msgType) { case MsgType.OK: return Show(msg, catpion, System.Windows.Forms.MessageBoxButtons.OK); case MsgType.Question: return Question(msg, catpion, System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button2); case MsgType.Warning: return Warning(msg, catpion, System.Windows.Forms.MessageBoxButtons.OK); case MsgType.Exception: Exception(msg); return System.Windows.Forms.DialogResult.OK; case MsgType.YesNoCancel: return Information(msg, catpion, System.Windows.Forms.MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button3); case MsgType.YesNo: return Information(msg, catpion, System.Windows.Forms.MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button2); default: return System.Windows.Forms.DialogResult.Cancel; } } /// <summary> /// Show message /// </summary> /// <param name="msg">news</param> /// <param name="ie">Message type</param> /// <returns>When the user needs to make a choice, return YES or NO, otherwise return, ok, cancel, etc.</returns> public static System.Windows.Forms.DialogResult ShowMsg(IWin32Window owner, string msg, MsgType msgType) { switch (msgType) { case MsgType.OK: return Show(msg, "information", System.Windows.Forms.MessageBoxButtons.OK); case MsgType.Question: return Question(msg, "confirm", System.Windows.Forms.MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button2); case MsgType.Warning: return Warning(msg, "caveat", System.Windows.Forms.MessageBoxButtons.OK); case MsgType.Exception: Exception(msg); return System.Windows.Forms.DialogResult.OK; case MsgType.YesNoCancel: return Information(msg, "please choose", System.Windows.Forms.MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button3); default: return System.Windows.Forms.DialogResult.Cancel; } } #region Show public static DialogResult Show(string text) { return DevExpress.XtraEditors.XtraMessageBox.Show(text); } public static DialogResult Show(string text, string caption) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption); } public static DialogResult Show(string text, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, MessageBoxIcon.Information); } public static DialogResult Show(IWin32Window owner, string text, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(owner, text, caption, buttons, MessageBoxIcon.Information); } public static DialogResult Show(string text, string caption, System.Windows.Forms.MessageBoxButtons buttons, MessageBoxIcon icon) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, icon); } public static DialogResult Show(IWin32Window owner, string text, string caption, System.Windows.Forms.MessageBoxButtons buttons, MessageBoxIcon icon) { return DevExpress.XtraEditors.XtraMessageBox.Show(owner, text, caption, buttons, icon); } #endregion #region Information public static DialogResult Information(string message) { return DevExpress.XtraEditors.XtraMessageBox.Show(message, " news", MessageBoxButtons.OK, MessageBoxIcon.Information); } public static DialogResult Information(string message, string caption) { return DevExpress.XtraEditors.XtraMessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); } public static DialogResult Information(string message, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(message, caption, buttons, MessageBoxIcon.Information); } public static DialogResult Information(string message, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defButton) { return DevExpress.XtraEditors.XtraMessageBox.Show(message, caption, buttons, MessageBoxIcon.Information, defButton); } #endregion #region Question public static DialogResult Question(string text) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, "doubt", MessageBoxButtons.OK, MessageBoxIcon.Question); } public static DialogResult Question(string text, string caption) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Question); } public static DialogResult Question(string text, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, MessageBoxIcon.Question); } public static DialogResult Question(string text, string caption, MessageBoxButtons buttons, MessageBoxDefaultButton defButton) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, MessageBoxIcon.Question, defButton); } #endregion #region Warning public static DialogResult Warning(string text) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, "caveat", MessageBoxButtons.OK, MessageBoxIcon.Warning); } public static DialogResult Warning(string text, string caption) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning); } public static DialogResult Warning(string text, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, MessageBoxIcon.Warning); } #endregion #region Exception public static DialogResult Exception(string text) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public static DialogResult Exception(string text, string caption) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } public static DialogResult Exception(string text, string caption, MessageBoxButtons buttons) { return DevExpress.XtraEditors.XtraMessageBox.Show(text, caption, buttons, MessageBoxIcon.Error); } #endregion #endregion