Force application close on system shutdown

前端 未结 5 1523
臣服心动
臣服心动 2020-12-29 22:18

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

相关标签:
5条回答
  • 2020-12-29 22:22

    you can use Application.SessionEnding Event to understand if the system is about to shutdown

    http://msdn.microsoft.com/en-us/library/system.windows.application.sessionending.aspx

    0 讨论(0)
  • 2020-12-29 22:35

    SystemEvents can help you. The SessionEnding occurs when the user is trying to log off or shut down the system.

    Microsoft.Win32.SystemEvents.SessionEnding += (sender, e) => DoYourJob();
    
    0 讨论(0)
  • 2020-12-29 22:38

    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.

    0 讨论(0)
  • 2020-12-29 22:43

    In the Closing event handler, which you can define like this:

        this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
    

    and where I guess you are posting your confirmation dialog, you can check theCloseReason argument, and not post the dialog if it is the shutdown that causes it:

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.WindowsShutDown)
            {
                //do not show the dialog
            }
        }
    
    0 讨论(0)
  • 2020-12-29 22:47

    You could listen for the shutdown event and quit the application without a message box.

    0 讨论(0)
提交回复
热议问题