Windows form application exit

Application. Exit Method

Definition

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Overloads

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Examples

The following code example lists numbers in a list box on a form. Each time you click button1 , the application adds another number to the list.

The Main method calls Run to start the application, which creates the form, listBox1 , and button1 . When the user clicks button1 , the button1_Click method adds numbers one to three to the list box, and displays a MessageBox. If the user clicks No on the MessageBox, the button1_Click method adds another number to the list. If the user clicks Yes, the application calls Exit, to process all remaining messages in the queue and then to quit.

The example requires that listBox1 and button1 have been instantiated and placed on a form.

Remarks

The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return. To exit a message loop for the current thread only, call ExitThread.

Exit raises the following events and performs the associated conditional actions:

A FormClosing event is raised for every form represented by the OpenForms property. This event can be canceled by setting the Cancel property of their FormClosingEventArgs parameter to true .

If one of more of the handlers cancels the event, then Exit returns without further action. Otherwise, a FormClosed event is raised for every open form, then all running message loops and forms are closed.

The Exit method does not raise the Closed and Closing events, which are obsolete as of .NET Framework 2.0.

Application. Exit Метод

Определение

Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Перегрузки

Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Сообщает всем средствам переноса сообщений, что они должны завершить работу, а затем закрывает все окна приложения после обработки сообщений. Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.

Примеры

В следующем примере кода показаны числа из списка в форме. The following code example lists numbers in a list box on a form. Каждый раз при щелчке button1 приложение добавляет в список еще один номер. Each time you click button1 , the application adds another number to the list.

Читайте также:  Изменять множитель процессора windows

Main Метод вызывает, Run чтобы запустить приложение, которое создает форму, listBox1 и button1 . The Main method calls Run to start the application, which creates the form, listBox1 , and button1 . Когда пользователь нажимает кнопку button1 , button1_Click метод добавляет числа от 1 до 3 в список и отображает MessageBox . When the user clicks button1 , the button1_Click method adds numbers one to three to the list box, and displays a MessageBox. Если пользователь нажимает кнопку нет в MessageBox , button1_Click метод добавляет еще один номер в список. If the user clicks No on the MessageBox, the button1_Click method adds another number to the list. Если пользователь нажмет кнопку Да, приложение вызывает Exit , чтобы обработать все оставшиеся сообщения в очереди и затем завершить работу. If the user clicks Yes, the application calls Exit, to process all remaining messages in the queue and then to quit.

Для примера требуется, чтобы listBox1 и button1 были созданы и помещены в форму. The example requires that listBox1 and button1 have been instantiated and placed on a form.

Комментарии

ExitМетод останавливает все выполняющиеся циклы сообщений во всех потоках и закрывает все окна приложения. The Exit method stops all running message loops on all threads and closes all windows of the application. Этот метод не обязательно приводит к принудительному завершению работы приложения. This method does not necessarily force the application to exit. ExitМетод обычно вызывается из цикла обработки сообщений и принудительно Run возвращает значение. The Exit method is typically called from within a message loop, and forces Run to return. Чтобы выйти из цикла обработки сообщений только для текущего потока, вызовите ExitThread . To exit a message loop for the current thread only, call ExitThread.

Exit вызывает следующие события и выполняет связанные условные действия: Exit raises the following events and performs the associated conditional actions:

FormClosingСобытие вызывается для каждой формы, представленной OpenForms свойством. A FormClosing event is raised for every form represented by the OpenForms property. Это событие можно отменить, задав Cancel для свойства своего параметра значение FormClosingEventArgs true . This event can be canceled by setting the Cancel property of their FormClosingEventArgs parameter to true .

Если один из обработчиков отменяет событие, а Exit возвращает без дальнейших действий. If one of more of the handlers cancels the event, then Exit returns without further action. В противном случае FormClosed событие вызывается для каждой открытой формы, после чего все выполняющиеся циклы сообщений и формы закрываются. Otherwise, a FormClosed event is raised for every open form, then all running message loops and forms are closed.

ExitМетод не вызывает Closed Closing события и, которые устарели в платформа .NET Framework 2,0. The Exit method does not raise the Closed and Closing events, which are obsolete as of .NET Framework 2.0.

Application. Application Exit Событие

Определение

Происходит при закрытии приложения. Occurs when the application is about to shut down.

Тип события

Примеры

В следующем примере кода показаны две формы и выход из приложения при закрытии обеих форм. The following code example displays two forms and exits the application when both forms are closed. Когда приложение запускается и завершает работу, сохраняется расположение каждой формы. When the application starts and exits, the position of each form is remembered. В этом примере показано использование ApplicationExit события для получения сведений о том, когда следует сохранять положение формы в файле и когда FileStream должно быть закрыто. This example demonstrates using the ApplicationExit event to know when the form positions should be persisted to the file, and when the FileStream should be closed.

Читайте также:  Поменять контрастность windows 10

Класс MyApplicationContext наследует от ApplicationContext и отслеживает, когда закрывается каждая форма, и завершает текущий поток, когда они оба. The class MyApplicationContext inherits from ApplicationContext and keeps track of when each form is closed, and exits the current thread when they both are. Класс запоминает расположение каждой формы при его закрытии. The class remembers the position of each form when it is closed. Когда ApplicationExit происходит событие, класс записывает позиции каждого пользователя в файл. When the ApplicationExit event occurs, the class writes the positions of each for the user to the file. Данные о положении формы хранятся в файле appdata.txt , созданном в расположении, определенном параметром UserAppDataPath . The form position data is stored in a file titled appdata.txt that is created in the location determined by UserAppDataPath. Main Метод вызывает, Application.Run(context) чтобы запустить приложение, используя ApplicationContext . The Main method calls Application.Run(context) to start the application given the ApplicationContext.

Этот код является выдержкой из примера, показанного в ApplicationContext обзоре класса. This code is an excerpt from the example shown in the ApplicationContext class overview. ApplicationContextПолный листинг кода см. в разделе. See ApplicationContext for the whole code listing.

Комментарии

Необходимо присоединить обработчики событий к ApplicationExit событию для выполнения необработанных, обязательных задач, прежде чем приложение прекратит работу. You must attach the event handlers to the ApplicationExit event to perform unhandled, required tasks before the application stops running. Можно закрыть файлы, открытые этим приложением, или удалить объекты, которые не были освобождены при сборке мусора. You can close files opened by this application, or dispose of objects that garbage collection did not reclaim.

Поскольку это статическое событие, необходимо отсоединить все обработчики событий, присоединенные к этому событию, в ApplicationExit самом обработчике событий. Because this is a static event, you must detach any event handlers attached to this event in the ApplicationExit event handler itself. Если вы не отсоединяете эти обработчики, они остаются прикрепленными к событию и продолжают потреблять память. If you do not detach these handlers, they will remain attached to the event and continue to consume memory.

Application. Application Exit Event

Definition

Occurs when the application is about to shut down.

Event Type

Examples

The following code example displays two forms and exits the application when both forms are closed. When the application starts and exits, the position of each form is remembered. This example demonstrates using the ApplicationExit event to know when the form positions should be persisted to the file, and when the FileStream should be closed.

The class MyApplicationContext inherits from ApplicationContext and keeps track of when each form is closed, and exits the current thread when they both are. The class remembers the position of each form when it is closed. When the ApplicationExit event occurs, the class writes the positions of each for the user to the file. The form position data is stored in a file titled appdata.txt that is created in the location determined by UserAppDataPath. The Main method calls Application.Run(context) to start the application given the ApplicationContext.

This code is an excerpt from the example shown in the ApplicationContext class overview. See ApplicationContext for the whole code listing.

Читайте также:  Версии линукс для начинающих

Remarks

You must attach the event handlers to the ApplicationExit event to perform unhandled, required tasks before the application stops running. You can close files opened by this application, or dispose of objects that garbage collection did not reclaim.

Because this is a static event, you must detach any event handlers attached to this event in the ApplicationExit event handler itself. If you do not detach these handlers, they will remain attached to the event and continue to consume memory.

Application. Exit Событие

Определение

Происходит непосредственно перед завершением работы приложения и его отменой. Occurs just before an application shuts down and cannot be canceled.

Тип события

Примеры

В следующем примере показано, как: The following example demonstrates how to:

Обработайте Exit событие. Handle the Exit event.

Проверьте и обновите ApplicationExitCode свойство объекта ExitEventArgs . Inspect and update the ApplicationExitCode property of the ExitEventArgs.

Запись записи в журнал приложения в изолированном хранилище. Write an entry to an application log in isolated storage.

Сохранение состояния приложения в изолированном хранилище. Persist the application state to isolated storage.

Комментарии

Приложение может завершить работу по одной из следующих причин: An application can shut down for either of the following reasons:

ShutdownМетод Application объекта вызывается либо явным образом, либо в соответствии со ShutdownMode свойством. The Shutdown method of the Application object is called, either explicitly or as determined by the ShutdownMode property.

Пользователь завершает сеанс путем выхода из системы или завершения его работы. The user ends the session by logging off or shutting down.

Можно определить, когда происходит завершение работы приложения, обрабатывая Exit событие, и при необходимости выполнить дополнительную обработку. You can detect when application shutdown occurs by handling the Exit event, and perform any additional processing as required.

Кроме того, можно выполнять Exit проверку или изменение кода выхода приложения, если вам не нужно вызывать его Shutdown явным образом. You can also handle Exit to inspect or change the application exit code when you don’t need to call Shutdown explicitly. Код выхода предоставляется из ApplicationExitCode свойства ExitEventArgs аргумента, который передается в Exit обработчик событий. The exit code is exposed from the ApplicationExitCode property of the ExitEventArgs argument that’s passed to the Exit event handler. При остановке работы приложения код выхода передается в операционную систему для последующей обработки. When the application stops running, the exit code is passed to the operating system for subsequent processing.

Если приложение обрабатывает событие, SessionEnding а затем отменяет его, Exit не вызывается и приложение продолжит выполнение в соответствии с режимом завершения работы. If your application handles the SessionEnding event and subsequently cancels it, Exit is not raised and the application continues running in accordance with the shutdown mode.

Код выхода можно задать из приложения браузера XAML (XBAP), хотя значение игнорируется. The exit code can be set from an XAML browser application (XBAP), although the value is ignored.

Для XBAP Exit вызывается в следующих случаях: For XBAPs, Exit is raised in the following circumstances:

Выполняется переход к XBAP из. An XBAP is navigated away from.

В Internet Explorer 7, когда вкладка, на которой размещается XBAP, закрыта. In Internet Explorer 7, when the tab that is hosting the XBAP is closed.

Закрывается браузер. When the browser is closed.

Во всех случаях значение ApplicationExitCode свойства игнорируется. In all cases, the value of the ApplicationExitCode property is ignored.

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