3

My program is starting with windows, I have such code to prevent exiting application when user hits exit button:

    protected override void OnClosing(CancelEventArgs e)
    {
        this.ShowInTaskbar = false;
        e.Cancel = true;
        this.Hide();
    }

It is working very well, but when I want to turn off computer, every time I get screen like 'One or more application cannot be exited. Cancel - Exit despite this.

How can I allow windows to normally exit my application, but also prevent user from exiting it when click red exit button?

Sam
  • 7,252
  • 16
  • 46
  • 65
Qentinios
  • 89
  • 1
  • 8
  • 4
    You better post an answer your self instead of adding an answer to your question.... http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/ – rene Nov 16 '14 at 11:38

2 Answers2

4

See How to detect Windows shutdown or logoff.

In the SessionEnded event handler, set a boolean like sessionEnded and in your OnClosing test for that value:

if (!sessionEnded)
{
    e.Cancel = true;
    this.Hide();
}
Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
1

This helped (thanks to CodeCaster):

    private static int WM_QUERYENDSESSION = 0x11;
    private static bool systemShutdown = false;
    protected override void WndProc(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_QUERYENDSESSION)
        {
            systemShutdown = true;
        }

        // If this is WM_QUERYENDSESSION, the closing event should be
        // raised in the base WndProc.
        base.WndProc(ref m);

    } //WndProc 

    protected override void OnClosing(CancelEventArgs e)
    {
        this.ShowInTaskbar = false;
        if (!systemShutdown)
        {
            e.Cancel = true;
            this.Hide();
        }
    }
Qentinios
  • 89
  • 1
  • 8