How to know "Why application is closing"?

Viewed 29

Back in BCB3 or BCB5, I seem to remember that there was a way to see why my app was closing. I would like to show a dialog box if the user closes it, but just gracefully close if the computer is rebooting. How can I know the reason for the shutdown of my app?

1 Answers

To differentiate the reason, you will have to manually intercept and handle the WM_(QUERY)ENDSESSION, WM_SYSCOMMAND, and WM_CLOSE window messages directly.

Though, at least in this case, WM_(QUERY)ENDSESION should suffice. You can have it set a flag that you can then look at in the Form's OnCloseQuery event, eg:

class TMyForm : public TForm
{
__published:
    ...
    void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose);
private:
    bool SystemIsShuttingDown;
protected:
    virtual void __fastcall WndProc(TMessage &Message);
    ...
};
void __fastcall TMyForm::FormCloseQuery(TObject *Sender, bool &CanClose)
{
    if (!SystemIsShuttingDown)
    {
        // display dialog....
    }
}

void __fastcall TMyForm::WndProc(TMessage &Message)
{
    if (Message.Msg == WM_QUERYENDSESSION)
        SystemIsShuttingDown = true;
    else if (Message.Msg == WM_ENDSESSION && Message.WParam == FALSE)
        SystemIsShuttingDown = false;
    TForm::WndProc(Message);
}
Related