You need to use subclassing and the only way to detect a log-off.
You will receive a WM_QUERYENDSESSION and you need to process that