The TSystemState singleton record

The TSystemState record can be used to alter the system's state.

Screenshot from IDE

Source Code

unit SystemState;

interface

uses SysUtils, Windows, Messages;

type
  TSystemState = record
    Handle: HWND;
    strict private
      procedure HandleNeeded;
    public type
      TMonitorState = (msOn = -1, msOff = 2, msLowPower = 1);
      TForcePolicy = (fpNoForce = 0, fpForceIfHung = EWX_FORCEIFHUNG,
        fpAlwaysForce = EWX_FORCE);
    public
      function LockWorkstation: boolean;
      function Logoff(ForcePolicy: TForcePolicy = fpNoForce;
        Reason: cardinal = 0): boolean;
      function Shutdown(ForcePolicy: TForcePolicy = fpNoForce;
        Reason: cardinal = 0): boolean;
      function Reboot(ForcePolicy: TForcePolicy = fpNoForce;
        Reason: cardinal = 0): boolean;
      function Suspend: boolean;
      function Hibernate: boolean;
      function StartScreenSaver: boolean;
      function SetMonitorState(MonitorState: TMonitorState): boolean;
      function ShowStartMenu: boolean;
  end;

var
  SystemState: TSystemState;

implementation

{ TSystemState }

function SetSuspendState(Hibernate, ForceCritical, DisableWakeEvent: boolean):
  boolean; stdcallexternal 'powrprof.dll' name 'SetSuspendState';

procedure TSystemState.HandleNeeded;
begin
  if not IsWindow(Handle) then
    raise Exception.Create('In order to use this function, you need first to specify' +
      ' a (essentially any) window handle in the Handle variable. In most cases,' +
      ' you can use Application.Handle or simply Handle if in a form class.');
end;

function TSystemState.Hibernate: boolean;
begin
  result := SetSuspendState(true, false, false);
end;

function TSystemState.LockWorkstation: boolean;
begin
  result := Windows.LockWorkStation;
end;

function TSystemState.Logoff(ForcePolicy: TForcePolicy = fpNoForce; Reason: cardinal = 0): boolean;
begin
  result := ExitWindowsEx(EWX_LOGOFF or ord(ForcePolicy), Reason);
end;

function TSystemState.Reboot(ForcePolicy: TForcePolicy = fpNoForce; Reason: cardinal = 0): boolean;
begin
  result := ExitWindowsEx(EWX_REBOOT or ord(ForcePolicy), Reason);
end;

function TSystemState.SetMonitorState(MonitorState: TMonitorState): boolean;
begin
  HandleNeeded;
  result := SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER,
    ord(MonitorState)) = 0;
end;

function TSystemState.ShowStartMenu: boolean;
begin
  HandleNeeded;
  result := SendMessage(Handle, WM_SYSCOMMAND, SC_TASKLIST, 0) = 0;
end;

function TSystemState.Shutdown(ForcePolicy: TForcePolicy = fpNoForce; Reason: cardinal = 0): boolean;
begin
  result := ExitWindowsEx(EWX_POWEROFF or ord(ForcePolicy), Reason);
end;

function TSystemState.StartScreenSaver: boolean;
begin
  HandleNeeded;
  result := SendMessage(Handle, WM_SYSCOMMAND, SC_SCREENSAVE, 0) = 0;
end;

function TSystemState.Suspend: boolean;
begin
  result := SetSuspendState(false, false, false);
end;

end.