2

I'm writing a very simple Delphi 2007 program that monitors system activities. The program just hooks a DLL procedure and has to simply wait until the system shutsdown since all the handling is done in the DLL callback. Is a windowless program since I even removed the {$APPTYPE CONSOLE} from the source. The code is very simple:

begin
 try
  // TODO -oUser -cConsole Main : Insert code here }
   // If load sucessfull
   If (LoadDLL ()) Then Begin

     // Hook
     _dllSetWindowsHookEx (LibHandle);
     If (_dllHooked ()) Then Begin
       Repeat
       Until .......what?;

       // Unhook
       _dllUnhookWindowsHookEx ();
       End;

     // Release
     UnloadDLL ()
     End
 except
   on E:Exception do
     Writeln(E.Classname, ': ', E.Message);
 end;
end.  

I checked this question and it seems that maybe this will work:

   Repeat
   Until GetSystemMetrics(SM_SHUTTINGDOWN) <> 0;

However it also seems that it will use a lot of CPU. Is there another PeekMessage/WaitForSingleObject like approach to properly quit the program at system shutdown?

alvaroc
  • 433
  • 5
  • 14
  • 1
    "However it also seems that it will use a lot of CPU" Add a sort of delay in there, such as `Sleep(100);` After all, it gets called repeatedly back-to-back. The more the delay, the less CPU it uses. But you don't want too large of a delay. – Jerry Dodge Dec 27 '19 at 16:03
  • 1
    `SM_SHUTTINGDOWN` is not supported. `WM_ENDSESSION` messsage would be its equivalent. – TLama Dec 27 '19 at 16:50
  • Might still be able to use `SetConsoleCtrlHandler` and do the app shutdown in the call back when appropriate. – Brian Dec 27 '19 at 17:08
  • 2
    You can't use SetConsoleCtrlHandler because SetWndowsHookEx, etc.. are user32. If the hook is just for detecting shutdown, remove it. Then if your process does not load user32/gid32, directly or indirectly, use SetConsoleCtrlHandler. Otherwise deploy a hidden window and run a message loop that would receive WM_ENDSESSION. – Sertac Akyuz Dec 27 '19 at 17:36
  • @TLama but I need the program to coninue running even if a user logs off – alvaroc Dec 27 '19 at 23:56
  • 6
    @alvaroc "*I need the program to coninue running even if a user logs off*" - the only way to do that is to write the program as a [service](https://learn.microsoft.com/en-us/windows/win32/services/service-programs). Delphi has a `TService` class for exactly this purpose. A service runs in the background, can run through user logins/logouts, and can receive notifications like `SERVICE_CONTROL_SESSIONCHANGE`, `SERVICE_CONTROL_SHUTDOWN`, `SERVICE_CONTROL_USERMODEREBOOT`, etc. – Remy Lebeau Dec 28 '19 at 04:48

0 Answers0