Windows forms how to close window

Form. Close Метод

Определение

Закрывает форму. Closes the form.

Исключения

Форма была закрыта при создании дескриптора. The form was closed while a handle was being created.

Нельзя вызывать этот метод из события Activated, если свойство WindowState задано как Maximized. You cannot call this method from the Activated event when WindowState is set to Maximized.

Комментарии

При закрытии формы все ресурсы, созданные в объекте, закрываются, и форма удаляется. When a form is closed, all resources created within the object are closed and the form is disposed. Можно предотвратить закрытие формы во время выполнения, обрабатывая Closing событие и установив Cancel свойство объекта, CancelEventArgs переданного в качестве параметра обработчику событий. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. Если закрываемая форма является начальной формой приложения, приложение завершается. If the form you are closing is the startup form of your application, your application ends.

Два условия, когда форма не удаляется Close , имеет значение, если (1) она является частью приложения с многодокументным интерфейсом (MDI), а форма не видна, и (2) форма была отображена с помощью ShowDialog . The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. В таких случаях необходимо вручную вызвать, Dispose чтобы пометить все элементы управления формы для сборки мусора. In these cases, you will need to call Dispose manually to mark all of the form’s controls for garbage collection.

Window. Close Метод

Определение

Вручную закрывает окно Window. Manually closes a Window.

Примеры

В следующем примере показан файл | меню выхода , обрабатываемого для явного вызова Close . The following example shows a File | Exit menu being handled to explicitly call Close.

Комментарии

WindowМожно закрыть с помощью одного из нескольких хорошо известных, предоставляемых системой механизмов, расположенных в его заголовке, в том числе: A Window can be closed using one of several, well-known, system-provided mechanisms located in its title bar, including:

Системное меню | Закрыть. System menu | Close.

Кнопка » Закрыть «. Close button.

WindowТакже можно закрыть с помощью одного из нескольких хорошо известных механизмов в клиентской области, предоставляемых разработчиками, включая: A Window can also be closed using one of several well-known mechanisms within the client area that are provided by developers, including:

Файл | выйти из главного окна. File | Exit on a main window.

Файл | Закрыть или кнопку Закрыть в дочернем окне. File | Close or a Close button on a child window.

Кнопки ОК и Отмена в диалоговом окне также предоставляются разработчиками, хотя, скорее всего, будет установлено DialogResult , которое автоматически закроет окно, открытое при вызове ShowDialog . OK and Cancel buttons on a dialog box are also developer-provided, although will likely set DialogResult, which automatically closes a window that was opened by calling ShowDialog.

Эти механизмы потребовали явного вызова Close для закрытия окна. These mechanisms require you to explicitly call Close to close a window.

Если окно, открытое путем вызова ShowDialog , и со Button IsCancel свойством, для которого задано значение true, автоматически закроется при нажатии кнопки, или если нажать клавишу ESC. If a window, opened by calling ShowDialog, and with a Button with its IsCancel property set to true, will automatically close when the button is either clicked, or ESC is pressed. Если окно было открыто с помощью Show , Close необходимо явно вызвать метод, например из Click обработчика событий для Button . If the window was opened using Show, however, Close must be explicitly called, such as from Click event handler for the Button.

Читайте также:  Linux file write error

Закрытие окна приводит к Closing возникновению события. Closing a window causes the Closing event to be raised. Если Closing событие не отменено, происходит следующее: If the Closing event isn’t canceled, the following occurs:

WindowУдаляется из Application.Windows (если Application объект существует). The Window is removed from Application.Windows (if an Application object exists).

WindowУдаляется из владельца, Window если отношение владельца и владелец было установлено до того, как Window было отображено и после открытия владельца Window . The Window is removed from the owner Window if the owner/owned relationship was established before the owned Window was shown and after the owner Window was opened.

Возникает событие Closed. The Closed event is raised.

Неуправляемые ресурсы, созданные объектом, Window уничтожаются. Unmanaged resources created by the Window are disposed.

Если ShowDialog был вызван для отображения Window , ShowDialog возвращает. If ShowDialog was called to show the Window, ShowDialog returns.

При закрытии Window вызывается закрытие всех окон, которыми он владеет. Closing a Window causes any windows that it owns to be closed. Кроме того, закрытие Window может привести к прекращению работы приложения в зависимости от того, как Application.ShutdownMode это свойство задано. Furthermore, closing a Window may cause an application to stop running depending on how the Application.ShutdownMode property is set.

Этот метод не может быть вызван, если окно размещается в браузере. This method cannot be called when a window is hosted in a browser.

C# Form.Close vs Form.Dispose

I am new to C#, and I tried to look at the earlier posts but did not find a good answer.

In a C# Windows Form Application with a single form, is using Form.Close() better or Form.Dispose() ?

MSDN says that all resources within the object are closed and the form is disposed when a Close is invoked. Inspite of which, I have come across several examples online which follow a Dispose rather than a Close.

Does one have an advantage over the other? Under which scenarios should we prefer one over the other?

7 Answers 7

This forum on MSDN tells you.

Form.Close() sends the proper Windows messages to shut down the win32 window. During that process, if the form was not shown modally, Dispose is called on the form. Disposing the form frees up the unmanaged resources that the form is holding onto.

If you do a form1.Show() or Application.Run(new Form1()) , Dispose will be called when Close() is called.

However, if you do form1.ShowDialog() to show the form modally, the form will not be disposed, and you’ll need to call form1.Dispose() yourself. I believe this is the only time you should worry about disposing the form yourself.

As a general rule, I’d always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a «using» block.

Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.

In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.

Читайте также:  Mac os для macbook air a1466

How I hide close button in c# windows form [duplicate]

I have a modal dialog, and need to hide the Close (X) button, but I cannot use ControlBox = false, because I need to keep the Minimize and Maximize buttons.

I need to hide just Close button, is there any way to do that?

3 Answers 3

Although you can disable the close button as the answers here (and to the duplicate question) have suggested by adding the CS_NOCLOSE style to the form’s window class, consider very seriously whether you really need to do that.

You still have to give the user some way of dismissing the modal dialog, presumably with buttons on the dialog itself. And since one of those buttons is probably «Cancel» or the equivalent, you should just make the Close (X) button do the same thing as «Cancel». (Handle the FormClosing or FormClosed event for your form if you want to customize the default behavior or do something special on closure.)

Note that the Windows UI guidelines for dialog boxes state explicitly that you should not disable the Close button because users expect to see it and it gives them a feeling of security that they can always safely «get out» of whatever popped up on the screen if they don’t want it:

  • Dialog boxes always have a Close button. Modeless dialogs can also have a Minimize button. Resizable dialogs can have a Maximize button.
  • Don’t disable the Close button. Having a Close button helps users stay in control by allowing them to close windows they don’t want.
    • Exception: For progress dialogs, you may disable the Close button if the task must run to completion to achieve a valid state or prevent data loss.
  • The Close button on the title bar should have the same effect as the Cancel or Close button within the dialog box. Never give it the same effect as OK.
  • If the title bar caption and icon are already displayed in a prominent way near the top of the window, you can hide the title bar caption and icon to avoid redundancy. However, you still have to set a suitable title internally for use by Windows.

Even with progress dialogs, which Microsoft calls out as an «exception» to this general rule, it’s often very desirable to make the operation cancellable.

Form. Closing Событие

Определение

Происходит при закрытии формы. Occurs when the form is closing.

Тип события

Примеры

В следующем примере используется Closing для проверки, изменился ли текст в TextBox . The following example uses Closing to test if the text in a TextBox has changed. Если это так, пользователю будет предложено сохранить изменения в файл. If it has, the user is asked whether to save the changes to a file.

Комментарии

ClosingСобытие является устаревшим, начиная с платформа .NET Framework 2,0; FormClosing вместо этого используйте событие. The Closing event is obsolete starting with the .NET Framework 2.0; use the FormClosing event instead.

Это Closing событие возникает при закрытии формы. The Closing event occurs as the form is being closed. Когда форма закрывается, освобождаются все ресурсы, созданные в объекте, и форма удаляется. When a form is closed, all resources created within the object are released and the form is disposed. Если отменить это событие, форма останется открытой. If you cancel this event, the form remains opened. Чтобы отменить закрытие формы, задайте для Cancel свойства объекта, CancelEventArgs переданного обработчику событий, значение true . To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

Читайте также:  Как включить dhcp kali linux

Когда форма отображается как модальное диалоговое окно, нажатие кнопки Закрыть (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и свойству, для которого DialogResult устанавливается значение DialogResult.Cancel . When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult.Cancel . Можно переопределить значение, присваиваемое DialogResult свойству, когда пользователь нажимает кнопку Закрыть , задавая DialogResult свойство в обработчике событий для события в Closing форме. You can override the value assigned to the DialogResult property when the user clicks the Close button by setting the DialogResult property in an event handler for the Closing event of the form.

При Close вызове метода для, Form отображаемого в виде немодального окна, нельзя вызвать Show метод, чтобы сделать форму видимой, поскольку ресурсы формы уже были освобождены. When the Close method is called on a Form displayed as a modeless window, you cannot call the Show method to make the form visible, because the form’s resources have already been released. Чтобы скрыть форму и сделать ее видимой, используйте Control.Hide метод. To hide a form and then make it visible, use the Control.Hide method.

Form.ClosedСобытия и Form.Closing не вызываются при Application.Exit вызове метода для выхода из приложения. The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. При наличии кода проверки в любом из этих событий, которые необходимо выполнить, следует вызывать Form.Close метод для каждой открытой формы по отдельности перед вызовом Exit метода. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling the Exit method.

Если форма является родительской MDI-формой, то Closing события всех дочерних форм MDI создаются до возникновения события родительской формы MDI Closing . If the form is an MDI parent form, the Closing events of all MDI child forms are raised before the MDI parent form’s Closing event is raised. Кроме того, Closed события всех дочерних форм MDI вызываются до того, как Closed будет вызвано событие родительской формы MDI. In addition, the Closed events of all MDI child forms are raised before the Closed event of the MDI parent form is raised. Отмена Closing события дочерней формы MDI не мешает Closing порождению события РОДИТЕЛЬСКОй MDI-формы. Canceling the Closing event of an MDI child form does not prevent the Closing event of the MDI parent form from being raised. Однако при отмене события будет задано true Cancel свойство объекта CancelEventArgs , которое передается в качестве параметра родительской форме. However, canceling the event will set to true the Cancel property of the CancelEventArgs that is passed as a parameter to the parent form. Чтобы принудительно закрыть все родительские и дочерние формы MDI, задайте Cancel для свойства значение false в родительской форме MDI. To force all MDI parent and child forms to close, set the Cancel property to false in the MDI parent form.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Оцените статью
Adblock
detector