Windows forms how to close window

Ok, so a Windows Forms class, WindowSettings, and the form has a "Cancel"-button. When the user clicks the button, the dialog DialogSettingsCancel will pop-up up and ask the user if he is sure he w...

You need the actual instance of the WindowSettings that’s open, not a new one.

Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn’t do anything because that new instance never has been shown.

Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

Something like this:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel();
    dialogSettingsCancel.OwningWindowSettings = this;
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

public WindowSettings OwningWindowSettings { get; set; }

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    if(OwningWindowSettings != null)
        OwningWindowSettings.Close();
}

This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

If the two are always connected, you should instead use a constructor parameter:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel(this);
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

WindowSettings _owningWindowSettings;

public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
    if(owningWindowSettings == null)
        throw new ArgumentNullException("owningWindowSettings");

    _owningWindowSettings = owningWindowSettings;
}

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

  1. HowTo
  2. C# Howtos
  3. Close Form in C#
  1. Close Form With the Application.Exit() Function in C#
  2. Close Form With the Form.Close() Function in C#

Close Form 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#Ezoic
  • RRS feed

    • Remove From My Forums
    • Question

    • I’m looking to close a windows form application while opening another one, but I cannot seem to find a way that’s as simple as the this.Close(). The only issue with this is that it closes the whole application, whereas I only want to close the specific
      window upon the button press. Any ideas? Thank you!

      • Moved by
        CoolDadTx
        Wednesday, March 29, 2017 4:53 PM
        Winforms related

    All replies

    • Hi,

      >>How to close windows form application?

      Please use the below code to close the application:

      Application.Exit();

      >>whereas I only want to close the specific window upon the button press.

      Do you mean that you want to close a specific form within another application from one that has been opened? As far as I know, we can close any form in one application, but it is impracticable if you want to close another application’s form, they
      are different projects and have different namespace, also you can only open one application at the same time.

      I’m sorry If my understanding is wrong and please provide more details for your problem. I’m willing to help you for more description.

      Hope it helps!

      Best Regards,

      Stanly


      MSDN Community Support.
      Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
      MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Чтобы
    скрыть форму
    вызовите
    метод Hide.

    В
    следующем примере кода показан способ
    скрытия формы frm1.

    glob.frm1.Hide();

    Внимание.
    При скрытии начальной формы вы не сможете
    без дополнительных команд закрыть
    приложение. Поэтому одновременоо с
    методом Hide для начальной формы
    прописывается команда ее открытия,
    привязанная к некоторому событию.

    Пример:
    Можно передать функцию закрытия
    приложения другой форме. Для этого в
    событии FormClosed для этой формы необходимо
    прописать метод Show для начальной фомы.

    private
    void Form2_FormClosed(object sender, FormClosedEventArgs e)

    {

    glob.frm1.Show();

    }

    Чтобы
    закрыть форму
    вызовите
    метод Close.

    В
    следующем примере кода показан способ
    закрытия формы frm1.

    glob.frm1.Close();

    Примечание1.
    При закрытии начальной формы будет
    закрыто приложение.

    Примечание2.
    При закрытии формы происходит ликвидация
    файловой переменной. Если закрытаяформа
    не является начальной и предполагается
    форму открывать неоднократно, то при
    открытии формы должны быть прописаны
    два метода: Show
    и new
    Form,
    например:

    glob.frm2
    = new Form2();

    glob.frm2.Show();

      1. Работа с элементами управления Windows Forms

    Элемент
    управления
    — это компонент на форме, использующийся
    для отображения сведений или ввода
    пользовательских данных. В
    ходе разработки и изменения пользовательского
    интерфейса приложений Windows Forms требуется
    добавлять, выравнивать и размещать
    элементы управления. Каждый тип элемента
    управления имеет собственный набор
    свойств, методов и событий, соответствующих
    определенному назначению. С элементами
    управления можно работать в конструкторе
    или добавлять их динамически во время
    выполнения с помощью кода.

    Существуют
    разнообразные элементы управления,
    которые можно разместить в Windows Forms в
    зависимости от требований конкретного
    приложения.

        1. Добавление элементов управления в формы Windows Forms

    Большинство
    форм разрабатываются путем добавления
    элементов управления на поверхность
    формы с целью создания пользовательского
    интерфейса.

    Чтобы
    нарисовать элемент управления в форме,
    выполните следующие действия.

    1. Откройте
      форму.

    2. В
      панели
      элементов
      щелкните элемент управления, который
      требуется добавить в форму.

    3. Щелкните
      место в форме, где должен располагаться
      левый верхний угол элемента управления,
      а затем перетащите указатель мыши на
      место, в котором должен располагаться
      правый нижний угол элемента управления.

    Элемент
    управления добавляется на форму в
    указанное место с указанными размерами.

    Примечание.
    Для каждого
    элемента управления существует размер,
    определенный по умолчанию. На форму
    можно добавить элемент управления,
    который будет иметь размер по умолчанию.
    Для этого требуется перетащить элемент
    управления из панели
    элементов на
    форму.

    Чтобы перетащить
    элемент управления в форму, выполните
    следующие действия.

    1. Откройте
      форму.

    2. В
      панели элементов
      щелкните требуемый элемент управления
      и перетащите его в форму.

    Элемент
    добавляется в форму в указанное место
    с размером по умолчанию.

    Примечание.
    Чтобы
    добавить элемент управления с размером
    по умолчанию в верхний левый угол формы,
    щелкните его два раза в панели
    элементов.

    Можно
    также добавлять элементы управления
    на форму динамически во время выполнения.
    В приведенном ниже примере элемент
    управления TextBox
    (текстовое поле) будет добавлен на форму
    после щелчка элемента управления Button
    (кнопка).

    Примечание.
    Для
    следующей процедуры требуется форма с
    уже расположенным в ней элементом
    управления Кнопка
    Button1.

    Чтобы
    добавить элемент управления в форму с
    помощью программных средств,
    необходимо
    в метод, который обрабатывает событие
    (например, Click
    для кнопки) в результате которого должен
    быть добавлен элемент управления,
    добавить код, идентичный приведенному
    ниже. В коде прописаны команды: добавление
    ссылки на переменную элемента управления,
    задание расположения (свойство Location)
    элемента управления и добавления самого
    элемента управления.

    private
    void button1_Click(object sender, System.EventArgs e)

    {

    TextBox myText = new
    TextBox();

    myText.Location
    = new Point(25,25);

    this.Controls.Add (myText);

    }

    Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

    • #
    • #
    • #
    • #
    • #
    • #
    • #
    • #
    • #
    • #
    • #

    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

    Стандартные способы:

    • кликнуть в правом верхнем углу красную кнопку «крестик»
    • комбинация клавиш Alt+F4
    • кликнуть правой кнопкой мыши в верхнем левом углу, выбрать из контекстного меню «Закрыть»

    Не стандартные способы:

    • с помощью красной кнопки «крестик» с использованием окна сообщения
    • через созданную кнопку
    • через созданную кнопку с использованием окна сообщения

    с помощью красной кнопки «крестик» с использованием окна сообщения

    Пользователь пытается закрыть программу стандартным способом, кликает на верхнюю правую кнопку «крестик», нажимает комбинацию клавиш Alt+F4 или в левом верхнем углу вызывает контекстное меню формы. Но программа сразу не закрывается, а появляется окно сообщения, в котором нужно подтвердить решение закрытия.
    Событие FormClosingEventArgs принимает параметр «е». Этот параметр имеет свойство Cancel. Если установить его в false, форма закроется, если в true — останется открытой.

    Скрыть

    Показать

    Копировать

      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 _0006 {
    •  public partial class Form1 : Form {
    •   public Form1() {
    •    InitializeComponent();
    •   }
    •  
    •   private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    •    DialogResult dialog = MessageBox.Show(
    •     "Вы действительно хотите выйти из программы?",
    •     "Завершение программы",
    •     MessageBoxButtons.YesNo,
    •     MessageBoxIcon.Warning
    •    );
    •    if(dialog == DialogResult.Yes) {
    •     e.Cancel = false;
    •    }
    •    else {
    •     e.Cancel = true;
    •    }
    •   }
    •  }
    • }

    через созданную кнопку

    Метод Close() в родительской форме закрывает все приложение.
    Метод Close() в дочерних формах закрывает только дочернюю форму.
    Метод Application.Exit() закрывает приложение, если вызывается как из родительской формы, так и из дочерних форм.

    Скрыть

    Показать

    Копировать

      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 _0007 {
    •  public partial class Form1 : Form {
    •   public Form1() {
    •    InitializeComponent();
    •   }
    •  
    •   private void button1_Click(object sender, EventArgs e) {
    •    this.Close();
    •    
    •   }
    •  }
    • }

    через созданную кнопку с использованием окна сообщения

    В этом примере мы добавим кнопку на форму, которая будет закрывать приложение. Но при нажатии на кнопку будет вызвано окно сообщений.

    Скрыть

    Показать

    Копировать

      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 _0008 {
    •  public partial class Form1 : Form {
    •   public Form1() {
    •    InitializeComponent();
    •   }
    •  
    •   private void button1_Click(object sender, EventArgs e) {
    •    DialogResult dialog = MessageBox.Show(
    •     "Вы действительно хотите выйти из программы?",
    •     "Завершение программы",
    •     MessageBoxButtons.YesNo,
    •     MessageBoxIcon.Warning
    •    );
    •    if(dialog == DialogResult.Yes) {
    •     this.Close();
    •     
    •    }
    •   }
    •  }
    • }

    Содержание

    1. Form. Close Метод
    2. Определение
    3. Исключения
    4. Комментарии
    5. Window. Close Метод
    6. Определение
    7. Примеры
    8. Комментарии
    9. C# Form.Close vs Form.Dispose
    10. 7 Answers 7
    11. How I hide close button in c# windows form [duplicate]
    12. 3 Answers 3
    13. Form. Closing Событие
    14. Определение
    15. Тип события
    16. Примеры
    17. Комментарии

    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.

    Закрытие окна приводит к 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.

    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 .

    Когда форма отображается как модальное диалоговое окно, нажатие кнопки Закрыть (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и свойству, для которого 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.

    Понравилась статья? Поделить с друзьями:
  • Windows forms designer is not supported for project targeting net core
  • Windows forms datetimepicker как выбрать время
  • Windows forms combobox значение по умолчанию
  • Windows forms checkedlistbox только один элемент
  • Windows forms c решение квадратного уравнения