Search code examples
c++windowseventslogoff

Stop application when user initiates a log off / shutdown operation


I have this application (Windows form application written in Visual C++) from a colleague of mine and I face some serious problems. The application is neither a service neither a normal application, I mean it has a GUI but most of the time it runs in background (it should react as a service but it's not). This application is preventing the user to log off, and I need to be able to do that.

I know that Windows sends the WM_QUERYENDSESSION message to all running applications when the user tries to log off. I have tried to catch this message on my WndProc() function and to kill the application by force but it only works once. When I login again and try to log off the operation is not terminated because my application won't close.

If I try to use SessionEnding event, the application is only put to the system tray and remains there without logging off but this I believe it's because the Form_Closing method performs this operation instead of closing the program (this was the requirement and I can't change that).

Maybe another useful information is that the application starts automatically because it has an entry in the HKLM registry and there are always 2 instances of this application running (one should supervise the other one and restart it in case of crash but not in case of "manually" shut down).

Any suggestions will be well received.

Thanks.


Solution

  • Yes, this problem is caused by the form's FormClosing event handler. You have to pay attention to the close reason and only cancel it when the user is closing the window. Like this:

        System::Void Form1_FormClosing(System::Object^  sender, System::Windows::Forms::FormClosingEventArgs^  e) {
            // Do this *only* when the user closes the window
            if (e->CloseReason == CloseReason::UserClosing) {
                e->Cancel = true;
                this->Hide();
                // etc...
            }
        }