C# How to terminate application.run() [closed]
I would like to know, how to terminate a program using, for example, the escape key. In general, what I have to do to stop it after the application.run(..)?
How can I insert this
private void myForm_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) {
if (e.KeyCode == Keys.Escape) {
App开发者_JAVA百科lication.Exit();
}
}
in the code below
static void Main()
{
using (WinForm new_form = new WinForm())
{
new_form.InitializeComponent();
new_form.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true);
new_form.InitializeDevice();
new_form.LoadSurfaces();
new_form.Set3D();
Application.Run(new_form);
}
}
Call the Application.Exit()
method.
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. TheExit
method is typically called from within a message loop, and forcesRun
to return. To exit a message loop for the current thread only, callExitThread
.
Exit
raises the following events and performs the associated conditional actions:
A
FormClosing
event is raised for every form represented by theOpenForms
property. This event can be canceled by setting the Cancel property of theirFormClosingEventArgs
parameter to true.If one of more of the handlers cancels the event, then
Exit
returns without further action. Otherwise, aFormClosed
event is raised for every open form, then all running message loops and forms are closed.
To do this when the Esc key is pressed, you might want to handle the KeyUp
event for your form:
private void myForm_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
}
If you're using WinForms
then go for Application.Exit().
If you're using WPF
then use Application.Current.Shutdown();
Just call Application.Exit()
or close all active forms. E.g. you could simply add Close();
to the KeyDown
event handler in your form.
精彩评论