How can we close the form with the x in the upper corner of the windows Form? When I press x, it exits the form but the program is still running in the background.
Loading
How can we close the form with the x in the upper corner of the windows Form? When I press x, it exits the form but the program is still running in the background.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Naimish MakwanaPosted Apr 20, 2023, 4:00 AM
Hello Mehmet,
To add a confirmation message with the "Yes" and "No" buttons to the FormClosing event handler, you can use the MessageBox.Show method with the MessageBoxButtons.YesNo option. Here is an example implementation:
In this implementation, if the user clicks the "No" button in the confirmation message, the form closing event is canceled and the application continues running. If the user clicks the "Yes" button, the application is terminated.
Thanks
Naimish Makwana
Sam HobbsPosted Apr 19, 2023, 7:48 PM
It depends on why the program does not exit when the x does not cause it too. You do not show the code so we dont know what is causing that. A good solution might be to remove some code, not add more.
Mehmet FatihPosted Apr 19, 2023, 6:18 PM
Thanks everybody. The problem has been solved with the code below.
Mehmet FatihPosted Apr 19, 2023, 5:40 PM
Thanks a lot Rajkiran Swain. This code works fine but how can we add confirm message for closing with the MessageBoxButtons.YesNo?
Tuhin PaulPosted Apr 19, 2023, 5:30 PM
By setting
e.Canceltofalse, you indicate that it is okay to close the form and that the program should exit. If you do not sete.Canceltofalse, the form will be hidden but the program will continue running in the background.Tuhin PaulPosted Apr 19, 2023, 5:29 PM
When you press the x in the upper corner of a Windows Form, it typically triggers the FormClosing event, which you can handle in your code to perform any necessary cleanup actions before the form is closed. The form is simply hidden rather than closed, which can result in your program still running in the background. To ensure that your program completely exits when the user clicks the x, you can handle the FormClosing event and set the e.Cancel property to false.
Rajkiran SwainPosted Apr 19, 2023, 4:52 PM