locked
how to tell when the computer is being shutdown or user is logging off? RRS feed

  • Question

  • I have a windows form that needs to stay open in the system tray.  Because of this, I have put code in the form closing event that causes the window to minimize instead of close when the user clicks the close button.  The form can be closed from the menu that appears when you right click on the system tray icon. 

    As a result of this form closing event (I believe), when I try to shut down the computer or log off, nothing happens b/c my window will not close.

    So I really need to know how to determine when the log off or shutdown or restart occurs so I can close the form.

    Any help would be greatly appreciated.
    Tuesday, February 19, 2008 3:56 PM

Answers

  • The FormClosing event makes this very simple. You can determine if it is a windows shutdown (that is tha same as log off or restart) through the FormClosingEventArgs. Something like this:

     

    Code Snippet

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)

    {

    if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.TaskManagerClosing)

    {

    Application.Exit();

    return;

    }

    // Else you will minimize to the task bar

    }

     

     

    Regards,

    Fábio

    Tuesday, February 19, 2008 5:13 PM

All replies

  • The FormClosing event makes this very simple. You can determine if it is a windows shutdown (that is tha same as log off or restart) through the FormClosingEventArgs. Something like this:

     

    Code Snippet

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)

    {

    if (e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.TaskManagerClosing)

    {

    Application.Exit();

    return;

    }

    // Else you will minimize to the task bar

    }

     

     

    Regards,

    Fábio

    Tuesday, February 19, 2008 5:13 PM
  • Wow.  Thank you so much! 
    Tuesday, February 19, 2008 5:19 PM
  • You are welcome .

    Glad to be of help

    Tuesday, February 19, 2008 5:27 PM