简体   繁体   中英

Exiting application on X button of form pressed

I have a modal form (login) which I want that on closing it using "X" button, force application to exit. I tried this:

在此处输入图片说明

private void Login_Deactivate(object sender, EventArgs e)
{
    Application.Exit();
}

this cause my application to exit on pressing login button (closing). but I want exiting only on "X" button of window. How can I do it?

Get rid of the Deactivate event, you don't need it.

The issue here is that you cannot tell that just the "X" button was pressed. What you really do is track all the other conditions that cause form close, and react when it's not one of those.

You should leverage the DialogResult enum, and allow the calling application to react, instead of trying to do it all in the Login form.

In your Login form constructor, set the property to None :

public Login()
{
    DialogResult = DialogResult.None;
}

Then, in your button handler for "OK", set the property: DialogResult = DialogResult.OK .

If you have a specific Cancel event, you can set DialogResult = DialogResult.Cancel .

Ultimately, you could have a FormClosing event in the Login form, in which you can check this value and react. But more importantly, your calling application can check the result from the login form and react there as well.

我认为您应该使用this.Parent.Application.Exit() ,它会杀死整个应用程序。

Instead of Deactivate event, subscribe to the " FormClosing " event of the "Login" form. Write the same code which you have written. Keep the Deactivate event only if it is required to close the Application when you click outside login form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM