Search code examples
windowsdelphiserviceshutdown

Detect shutdown as SYSTEM user


I have an application that is started by a service. The application has no User Interface, it contains a DataModule and a TMyApplication implementation that calls Forms.Application.HandleMessage in a loop (like SvcMgr.TServiceApplication). I hooked the MainWindow to log any messages the hidden window of Forms.Application receives.

  • If I manually start the application so it runs on my useraccount, I receive WM_QUERYENDSESSION and WM_ENDSESSION messages on the hidden window of Forms.Application when logging off/shutting down.
  • If I start my application using the service, the application runs under the SYSTEM account. When running under the system account I receive only one message, $0000001A (WM_WININICHANGE?), at systemshutdown before my application is forcefully terminated by Windows. So no WM_QUERYENDSESSION and WM_ENDSESSION messages.

How can I detect a Windows shutdown on a SYSTEM account and close my application gracefully?


Solution

  • Have your service notify your sub-application.

    Here's some information about how the service control manager notifies your service:

    http://social.msdn.microsoft.com/Forums/en/netfxbcl/thread/063cef3a-de94-44d5-8f2e-4e63c3cfdee8

    Do a FindWindow, and PostMessage(hwnd, WM_ENDSESSION) yourself.