Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force application close on system shutdown

I have a Windows Forms application that when the Main Window is closing, it displays a basic dialog box, confirming the action. If the user decides to cancel the application exit is cancelled.

However, when the application is running minimized and the user wants to shut down the PC, the shutdown sequence stops because my application is waiting on the user to confirm the application close (the dialog box is displayed).

I thought of adding a timer for making a timeout and if no answer comes in a certain amount of time, close the application automatically, but even if this is a way to do it, it's certainly NOT how every other app does it.

So what would there be an optimal solution to confirm the application shutdown in every other case, unless the system is shutting down?

Thank you!

like image 928
Jano Rajmond Avatar asked Nov 15 '11 13:11

Jano Rajmond


People also ask

How do I close all programs on shutdown?

Close all open programsPress Ctrl-Alt-Delete and then Alt-T to open Task Manager's Applications tab. Press the down arrow, and then Shift-down arrow to select all the programs listed in the window. When they're all selected, press Alt-E, then Alt-F, and finally x to close Task Manager.

How do I close apps that are open in my system?

If you're wondering how to close a window without a mouse, there is a popular keyboard shortcut designed just for that. With the app open, press the keys Alt + F4. The app is immediately closed.


1 Answers

In your FormClosing event check the FormClosingEventArgs' CloseReason property to see why the window is closing down. If it is CloseReason.WindowsShutDown then don't show your dialog and do not cancel the closing of your form.

private void MyForm_FormClosing(object sender, FormClosingEventArgs e) {     // Verify that we're not being closed because windows is shutting down.     if (e.CloseReason != CloseReason.WindowsShutDown)     {         // Show your dialog / cancel closing.      } } 

N.B: You might also want to include CloseReason.TaskManagerClosing as the user clearly wants to close your application in that scenario and the taskmanager already asks for confirmation. Or alternatively only show your dialog for CloseReason.UserClosing.

like image 125
Johannes Kommer Avatar answered Sep 20 '22 22:09

Johannes Kommer