Windows forms form events

Form. Closing Event

Definition

Occurs when the form is closing.

Event Type

Examples

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.

Remarks

The Closing event is obsolete starting with the .NET Framework 2.0; use the FormClosing event instead.

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. To cancel the closure of a form, set the Cancel property of the CancelEventArgs passed to your event handler to true .

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 . 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.

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. To hide a form and then make it visible, use the Control.Hide method.

The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. 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.

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. In addition, the Closed events of all MDI child forms are raised before the Closed event of the MDI parent form is raised. Canceling the Closing event of an MDI child form does not prevent the Closing event of the MDI parent form from being raised. However, canceling the event will set to true the Cancel property of the CancelEventArgs that is passed as a parameter to the parent form. 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 во время выполнения How to: Create Event Handlers at Run Time for Windows Forms

Помимо создания событий с помощью конструктор Windows Forms в Visual Studio можно также создать обработчик событий во время выполнения. In addition to creating events using the Windows Forms Designer in Visual Studio, you can also create an event handler at run time. Это позволит подключать обработчики событий в зависимости от условий в коде во время выполнения, а не при начальном запуске программы. This action allows you to connect event handlers based on conditions in code at run time as opposed to having them connected when the program initially starts.

Читайте также:  Куда сохраняется фрагмент экрана windows 10

Создание обработчика событий во время выполнения Create an event handler at run time

Откройте форму, в которую нужно добавить обработчик событий. Open the form that you want to add an event handler to.

Добавьте метод в форму с сигнатурой метода для события, которое будет необходимо обрабатывать. Add a method to your form with the method signature for the event that you want to handle.

Например, при обработке Click события Button элемента управления необходимо создать метод, подобный следующему: For example, if you were handling the Click event of a Button control, you would create a method such as the following:

Добавьте код в обработчик событий в зависимости от приложения. Add code to the event handler as appropriate to your application.

Определите форму или элемент управления, для которого необходимо создать обработчик событий. Determine which form or control you want to create an event handler for.

В методе внутри класса формы добавьте код, в соответствии с которым обработчик событий будет обрабатывать событие. In a method within your form’s class, add code that specifies the event handler to handle the event. Например, следующий код указывает обработчик событий button1_Click , обрабатывающий Click событие Button элемента управления: For example, the following code specifies the event handler button1_Click handles the Click event of a Button control:

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.

Читайте также:  Apache server под windows

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.

Form. Closed Событие

Определение

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

Тип события

Примеры

В следующем примере показано, как использовать SetDesktopLocation элементы, Closed , Load , Activated и Activate . The following example demonstrates how to use the SetDesktopLocation, Closed, Load, Activated, and Activate members. Чтобы выполнить пример, вставьте следующий код в форму с именем, Form1 которая содержит Button вызываемый метод Button1 , и два Label элемента управления с именем Label1 и Label2 . To run the example, paste the following code in a form called Form1 containing a Button called Button1 and two Label controls called Label1 and Label2 .

Комментарии

ClosedСобытие является устаревшим в платформа .NET Framework версии 2,0; используйте FormClosed событие. The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead.

Это событие происходит после закрытия формы пользователем или Close методом формы. This event occurs after the form has been closed by the user or by the Close method of the form. Чтобы предотвратить закрытие формы, обработайте Closing событие и задайте Cancel для свойства объекта, CancelEventArgs переданного обработчику событий, значение true . To prevent a form from closing, handle the Closing event and set the Cancel property of the CancelEventArgs passed to your event handler to true .

Это событие можно использовать для выполнения таких задач, как освобождение ресурсов, используемых формой, и сохранения информации, введенной в форму, или для обновления ее родительской формы. You can use this event to perform tasks such as freeing resources used by the form and to save information entered in the form or to update its parent form.

Читайте также:  Flutter install mac os

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.

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

Using keyboard events (Windows Forms .NET)

Most Windows Forms programs process keyboard input by handling the keyboard events. This article provides an overview of the keyboard events, including details on when to use each event and the data that is supplied for each event. For more information about events in general, see Events overview (Windows Forms .NET).

The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Keyboard events

Windows Forms provides two events that occur when a user presses a keyboard key and one event when a user releases a keyboard key:

  • The KeyDown event occurs once.
  • The KeyPress event, which can occur multiple times when a user holds down the same key.
  • The KeyUp event occurs once when a user releases a key.

When a user presses a key, Windows Forms determines which event to raise based on whether the keyboard message specifies a character key or a physical key. For more information about character and physical keys, see Keyboard overview, keyboard events.

The following table describes the three keyboard events.

Keyboard event Description Results
KeyDown This event is raised when a user presses a physical key. The handler for KeyDown receives:
  • A KeyEventArgs parameter, which provides the KeyCode property (which specifies a physical keyboard button).
  • The Modifiers property (SHIFT, CTRL, or ALT).
  • The KeyData property (which combines the key code and modifier). The KeyEventArgs parameter also provides:
  • The Handled property, which can be set to prevent the underlying control from receiving the key.
  • The SuppressKeyPress property, which can be used to suppress the KeyPress and KeyUp events for that keystroke.
KeyPress This event is raised when the key or keys pressed result in a character. For example, a user presses SHIFT and the lowercase «a» keys, which result in a capital letter «A» character. KeyPress is raised after KeyDown.
  • The handler for KeyPress receives:
  • A KeyPressEventArgs parameter, which contains the character code of the key that was pressed. This character code is unique for every combination of a character key and a modifier key.
Оцените статью