in reply to Controlling a program in Windows

See this discussion. The messages WM_QUERYENDSESSION and WM_ENDSESSION look like what you need.