Subclass your main form and look for the WM_QUERYENDSESSION
message. This is what the systems sends while shutting down the system