unit FDCRelauncher; /// Simple mechanisms for restarting a service or application on exit. /// Intended for use after .exe upgrades, etc. /// Instructions: /// 1. Put the unit as early as possible in the main app uses section /// 2. Call one of the Restart procedures before exiting. /// /// Written by Lars Fosdal, Tine SA, 15 OCT 2014, http://plus.lars.fosdal.com interface uses Windows, SysUtils, ShellAPI, CustomDebugOut; /// Restarts the application on exit, optionally passing extra arguments on the command line procedure RestartApplicationOnExit(const aExtraArguments: String = ''); /// Restarts the service when it stops, using service name (without quotes) procedure RestartServiceOnExit(const ServiceName: String); implementation type TRestartOnExit = reference to procedure; var RestartOnExit: TRestartOnExit; procedure RestartServiceOnExit(const ServiceName: String); begin RestartOnExit := procedure begin OutputDebugString(SysEvent + 'Restarting ' + ServiceName); try ShellExecute(0, 'open', pChar('cmd.exe'), pChar('/S /C net start "' + ServiceName + '"'), nil, SW_HIDE); except on E:Exception do begin OutputDebugString(BadShit + 'Restart Service Exception ' + E.ClassName + ' ' + E.Message); end; end; end; end; procedure RestartApplicationOnExit(const aExtraArguments: String); var ExtraArguments: String; begin ExtraArguments := Trim(aExtraArguments); RestartOnExit := procedure begin OutputDebugString(SysEvent + 'Restarting ' + ExtraArguments); try ShellExecute(0, 'open', pChar(ParamStr(0)), pChar('RestartApplicationOnExit='+IntToStr(GetCurrentProcessId) + ExtraArguments), nil, SW_NORMAL); except on E:Exception do begin OutputDebugString(BadShit + 'Restart Application Exception ' + E.ClassName + ' ' + E.Message); end; end; end; end; initialization RestartOnExit := nil; finalization if Assigned(RestartOnExit) then RestartOnExit; end.