(************************************************************************
*    This File is Part of the AHM Triton Tools                          *
*    for Borland Delphi and C++ Builder.                                *
*************************************************************************
* Copyright © 1995-1999 Alexander H. Mehlhorn (AHM) and Tritontools.com *
* All Rights reserved.                                                  *
*                                                                       *
*    For more Information contact us at                                 *
*    E-Mail : support@tritontools.com                                   *
*    URL : http://www.tritontools.com                                   *
*                                                                       *
*    AHM is copyright by Alexander H. Mehlhorn                          *
*    All Parts of this Collection were developed,                       *
*    designed and implemented by AHM                                    *
*                                                                       *
*    Under no Circumstances may you distribute this file                *
*    in this or any other format. This File is supplied                 *
*    as Evaluation of Source only. No Delphi Components may be developed*
*    using extracts or subsets of this code without expressed permission*
*    by AHM.                                                            *
*                                                                       *
*************************************************************************)
unit AHMTSystemManager;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  AHMSystemConst,AHMSystemClass;
{$I AHM.INC}
type
  TAHMSystemManager = class;
  TAHMWinWallPaper = class(TPersistent)
  private
    FTiled: Boolean;
    FFileName: String;
  protected
  public
    Function Execute : Boolean;
    constructor Create; virtual;
  published
    property BmpFilename : String read FFileName write FFileName;
    property Tiled : Boolean read FTiled write FTiled default True;
  end;
  TAHMScreenSave = class(TPersistent)
  private
    function GetActive: Boolean;
    function GetSeconds: Longint;
    procedure SetActive(const Value: Boolean);
    procedure SetSeconds(const Value: Longint);
  protected
  public
  published
    property Seconds : Longint read GetSeconds write SetSeconds stored False;
    property Installed : Boolean read GetActive write SetActive stored False;
  end;
  TAHMExitType = (xLogoff, xReboot, xShutDown, xPowerOff, xForce);
  TAHMShutdown = class(TPersistent)
  private
    FAHMSystemManager : TAHMSystemManager;
    FConfirm: Boolean;
    FConfirmation: String;
    FExittype: TAHMExitType;
  protected
  public
    constructor Create(AOwner : TAHMSystemManager); virtual;
    destructor destroy; override;
    Function Execute : Integer;
  published
    property Confirm : Boolean read FConfirm write FConfirm default True;
    property Confirmation : String read FConfirmation write FConfirmation;
    property Exittype : TAHMExitType read FExittype write FExittype default xReboot;
  end;
  TAHMSysKeys = class(TPersistent)
  private
    procedure SetCapsLock(Const value : Boolean );
    procedure SetNumLock(Const value : Boolean );
    procedure SetScrollLock(Const value : Boolean );
    function GetCapsLock : Boolean;
    function GetScrollLock : Boolean;
    function GetNumLock : Boolean;
  protected
  public
  published
    property CapsLock: Boolean read GetCapsLock write SetCapsLock stored False;
    property NumLock: Boolean read GetNumLock write SetNumLock stored False;
    property ScrollLock: Boolean read GetScrollLock write SetScrollLock stored False;
  end;
  TAHMOnErrorShutdown =procedure (Sender:TObject;Error : Integer) of object;
  TAHMSystemOptions = class(TPersistent)
  private
    FWinIcons: Boolean;
    FWinOfficeBar: Boolean;
    FWinTaskBar: Boolean;
    FMinimizeAll: Boolean;
    FAHMSystemManager : TAHMSystemManager;
    function pGetWinAnimation: Boolean;
    function pGetWinDragFull: Boolean;
    procedure SetWinAnimation(const Value: Boolean);
    procedure SetWinDragFull(const Value: Boolean);
    function GetFontSmoothing: Boolean;
    function GetWarningBeep: Boolean;
    procedure SetFontSmoothing(const Value: Boolean);
    procedure SetWarningbeep(const Value: Boolean);
    function GetSnapToDefaultBtn: Boolean;
    procedure SetSnapToDefaultBtn(const Value: Boolean);
    procedure SetWinIcons(const Value: Boolean);
    procedure SetWinOfficeBar(const Value: Boolean);
    procedure SetWinTaskbar(const Value: Boolean);
    procedure SetMinimizeAll(const Value: Boolean);
  public
    constructor Create(AOwner: TAHMSystemManager); virtual;
    Destructor Destroy; override;
  published
    property pAnimation : Boolean read pGetWinAnimation write SetWinAnimation stored False;
    property pDragFullWindows : Boolean read pGetWinDragFull write SetWinDragFull stored False;
    property pFontSmoothing : Boolean read GetFontSmoothing write SetFontSmoothing stored False;
    property pSnapToDefaultBtn : Boolean read GetSnapToDefaultBtn write SetSnapToDefaultBtn stored False;
    property pWarningbeep : Boolean read GetWarningBeep write SetWarningbeep stored False;
    property pTaskBar : Boolean read FWinTaskBar write SetWinTaskbar stored False;
    property pIcons : Boolean read FWinIcons write SetWinIcons stored False;
    property pOfficeBar : Boolean read FWinOfficeBar write SetWinOfficeBar stored False;
    property pDoMinimizeAll : Boolean read FMinimizeAll write SetMinimizeAll stored False;
  end;
  TAHMSystemManager = class(TAHMSystemsComponent)
  private
    FSystemKeys: TAHMSysKeys;
    FOnErrorShutdown: TAHMOnErrorShutdown;
    FOnCallShutdown: TNotifyEvent;
    FShutdown: TAHMShutdown;
    FScreenSaver: TAHMScreenSave;
    FWallPaper: TAHMWinWallPaper;
    FAHMSystemOptions: TAHMSystemOptions;
    { Private declarations }
  protected
    { Protected declarations }
  public
    { Public declarations }
    Function EmptyBin(Confirmation,Progress,Sound : Boolean) : Boolean;
    function CallShutdown: LongInt;
    function CallScreenSaver: Boolean;
    function SetWallPaper: Boolean;
    function DoHideWindow(ATaskName: PChar; AVisible: Boolean): Boolean;
    Constructor Create(AOwner : TComponent); override;
    Destructor Destroy; override;
  published
    { Published declarations }
    Property Properties : TAHMSystemOptions read FAHMSystemOptions write FAHMSystemOptions;
    Property SystemKeys : TAHMSysKeys read FSystemKeys write FSystemKeys;
    Property ScreenSaver : TAHMScreenSave read FScreenSaver write FScreenSaver;
    Property Shutdown : TAHMShutdown read FShutdown write FShutdown;
    Property WallPaper : TAHMWinWallPaper read FWallPaper write FWallPaper;
    property OnCallShutdown : TNotifyEvent read FOnCallShutdown write FOnCallShutdown;
    property OnErrorShutdown : TAHMOnErrorShutdown read FOnErrorShutdown write FOnErrorShutdown;
  end;

Function AHMExitWindows(const Flags : Integer) : LongInt;
Procedure AHMSetWallPaper(FileName : String;IsTiled : Boolean);
Function MinimizeAllWindows : Boolean;

implementation
uses Registry;

type
   PFNEmptyBin = ^TFNEmptyBin;
   TFNEmptyBin = function(HWND:hwnd;pszRootPath:PAnsiChar;DFlags :DWord): DWORD; stdcall;

const
   SHERB_NOCONFIRMATION  = $00000001;
   SHERB_NOPROGRESSUI    = $00000002;
   SHERB_NOSOUND         = $00000004;
Var
   AHMEmptyBin : TFNEmptyBin = nil;

Function AHMIsWinNt : Boolean;
Var OSVersionInfo : TOSVersionInfo;
begin
  result:=False;
  FillChar(OSVersionInfo,SizeOf(OSVersionInfo),0);
  OSVersionInfo.dwOSVersionInfoSize := sizeof(TOSVERSIONINFO);
  GetVersionEx(OSVersionInfo);
  case OSVersionInfo.dwPlatformID of
    VER_PLATFORM_WIN32_NT      : result:=True;
  end;
end;

function SHEmptyRecycleBin(HWND:hwnd;pszRootPath:PAnsiChar;DFlags :DWord): DWORD;
Var BinModule : HModule;
begin
  Result := 200;
  BinModule := LoadLibrary(PChar(ahmscshell32));
  if BinModule<>0 then
  begin
    if @AHMEmptyBin = nil then @AHMEmptyBin := GetProcAddress(BinModule,PChar(ahmscemptybin));
    if @AHMEmptyBin <> nil then
    Result := AHMEmptyBin(HWND,pszRootPath,DFlags);
  end;
  if BinModule <> 0 then FreeLibrary(BinModule);
end;

function TAHMSystemManager.EmptyBin(Confirmation, Progress,
  Sound: Boolean): Boolean;
begin
  result:=SHEmptyRecycleBin(Application.Handle,'',(Integer(not(Confirmation))*SHERB_NOCONFIRMATION) or
                                                  (Integer(not(Sound))*SHERB_NOSOUND) or
                                                  (Integer(not(Progress))*SHERB_NOPROGRESSUI))=S_OK;
end;

constructor TAHMSystemManager.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FSystemKeys:=TAHMSysKeys.Create;
  FShutdown:=TAHMShutdown.Create(Self);
  FScreensaver := TAHMScreenSave.Create;
  FWallPaper:=TAHMWinWallPaper.Create;
  FAHMSystemOptions:=TAHMSystemOptions.Create(Self);
end;


destructor TAHMSystemManager.Destroy;
begin
  FSystemKeys.Free;
  FShutdown.Free;
  FScreenSaver.Free;
  FWallPaper.Free;
  FAHMSystemOptions.Free;
  inherited Destroy;
end;

{ TAHMSysKeys }
function TAHMSysKeys.GetCapsLock : Boolean;
var KeyState : TKeyboardState;
begin
  GetKeyboardState(KeyState);
  result := Boolean(KeyState[VK_CAPITAL]);
end;

function TAHMSysKeys.GetScrollLock : Boolean;
var KeyState : TKeyboardState;
begin
  GetKeyboardState(KeyState);
  result := Boolean(KeyState[VK_SCROLL]);
end;

function TAHMSysKeys.GetNumLock : Boolean;
var KeyState : TKeyboardState;
begin
  GetKeyboardState(KeyState);
  result := Boolean(KeyState[VK_NUMLOCK]);
end;


procedure TAHMSysKeys.SetCapsLock(Const Value : Boolean);
var KeyboardState: TKeyboardState;
begin
  if AHMIsWinNT then
  begin
    keybd_event(VK_CAPITAL, $45, KEYEVENTF_EXTENDEDKEY or 0, 0);
    keybd_event(VK_CAPITAL, $45, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
  end else
  begin
    GetKeyboardState(KeyboardState);
    KeyboardState[VK_CAPITAL]:= Integer(Value);
    SetKeyboardState(KeyboardState);
  end;
end;

procedure TAHMSysKeys.SetNumLock(Const Value : Boolean);
var KeyboardState: TKeyboardState;
begin
  if AHMIsWinNT then
  begin
    keybd_event(VK_NUMLOCK, $45, KEYEVENTF_EXTENDEDKEY or 0, 0);
    keybd_event(VK_NUMLOCK, $45, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
  end else
  begin
    GetKeyboardState(KeyboardState);
    KeyboardState[VK_NUMLOCK]:= Integer(Value);
    SetKeyboardState(KeyboardState);
  end;
end;

procedure TAHMSysKeys.SetScrollLock(Const Value : Boolean);
var KeyboardState: TKeyboardState;
begin
  if AHMIsWinNT then
  begin
    keybd_event(VK_SCROLL, $45, KEYEVENTF_EXTENDEDKEY or 0, 0);
    keybd_event(VK_SCROLL, $45, KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
  end else
  begin
    GetKeyboardState(KeyboardState);
    KeyboardState[VK_SCROLL]:= Integer(Value);
    SetKeyboardState(KeyboardState);
  end;
end;

{ TAHMShutdown }

constructor TAHMShutdown.Create(AOwner: TAHMSystemManager);
begin
  inherited Create;
  FConfirm:=True;
  FExitType:=xReboot;
  FAHMSystemManager:=AOwner;
  FConfirmation:=ahmscshutdownconf;
end;


function AHMShutdownPrivilege(privilegeName: string; enable: boolean): boolean;
var tpPrev,tp         : TTokenPrivileges;
    token      : THandle;
    dwRetLen   : DWord;
begin
  result := False;
  {$IFDEF AHMINPRISE3}
  OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, token);
  {$ELSE}
  OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, @token);
  {$ENDIF}
  tp.PrivilegeCount := 1;
  if LookupPrivilegeValue(nil, pchar(privilegeName), tp.Privileges[0].LUID) then
  begin
    if enable then tp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
              else tp.Privileges[0].Attributes := 0;
    dwRetLen := 0;
    result := AdjustTokenPrivileges(token, False, tp, SizeOf(tpPrev), tpPrev, dwRetLen);
  end;
  CloseHandle(token);
end;

Function AHMExitWindows(const Flags : Integer) : LongInt;
begin
  AHMShutdownPrivilege(ahmscshutdownpriv, true);
  if not ExitWindowsEx(Flags, 0) then Result := GetLastError else Result:=0;
  AHMShutdownPrivilege(ahmscshutdownpriv, False);
end;

destructor TAHMShutdown.destroy;
begin
  FAHMSystemManager:=nil;
  inherited Destroy;
end;

function TAHMShutdown.Execute: Integer;
begin
  Result:=0;
  if not(FConfirm) then
  begin
    case FExitType of
       xLogoff   : Result := AHMExitWindows(EWX_LOGOFF);
       xReboot   : Result := AHMExitWindows(EWX_REBOOT);
       xShutDown : Result := AHMExitWindows(EWX_SHUTDOWN);
       xPowerOff : Result := AHMExitWindows(EWX_POWEROFF);
       xForce    : Result := AHMExitWindows(EWX_FORCE);
    end;
    if Result=0 then Application.Terminate;
  end else
  if MessageDlg(FConfirmation,mtconfirmation,[mbYes,mbNo],0)=mrYes then
  begin
    case FExitType of
       xLogoff   : Result := AHMExitWindows(EWX_LOGOFF);
       xReboot   : Result := AHMExitWindows(EWX_REBOOT);
       xShutDown : Result := AHMExitWindows(EWX_SHUTDOWN);
       xPowerOff : Result := AHMExitWindows(EWX_POWEROFF);
       xForce    : Result := AHMExitWindows(EWX_FORCE);
    end;
    if Result=0 then Application.Terminate;
  end else Result:=0;
end;

function TAHMSystemManager.CallShutdown: LongInt;
begin
  if assigned(FOnCallShutdown) then FOnCallShutdown(self);
  result:=FShutdown.Execute;
  if result<>0 then
  if assigned(FOnErrorShutdown) then FOnErrorShutdown(self,result);
end;


{ TAHMScreenSave }

procedure TAHMScreenSave.SetActive(Const Value : Boolean);
begin
  SystemParametersInfo(SPI_SETSCREENSAVEACTIVE,integer(value),nil,SPIF_SENDWININICHANGE);
end;

Function TAHMScreenSave.GetActive: Boolean;
var ii : integer;
begin
  SystemParametersInfo(SPI_GETSCREENSAVEACTIVE,0,@ii,0);
  result:=boolean(ii);
end;

Function TAHMScreenSave.GetSeconds : integer;
var ii : integer;
begin
  SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT,0,@ii,0);
  result:=ii;
end;

procedure TAHMScreenSave.SetSeconds(Const Value : Integer);
begin
  SystemParametersInfo(SPI_SETSCREENSAVETIMEOUT,value,nil,SPIF_SENDWININICHANGE);
end;


function TAHMSystemManager.CallScreenSaver: Boolean;
begin
  result:=true;
  if FScreenSaver.Installed then
  Sendmessage(Application.Handle,WM_SYSCOMMAND, SC_SCREENSAVE, 0) else result:=False;
end;

{ TAHMWinWallPaper }

Procedure AHMSetWallPaper(FileName : String;IsTiled : Boolean);
var PasFileName: Array[0..255] of char;

begin
  with TRegistry.Create do
  try
    OpenKey(ahmscwallpaperpath,FALSE);
    if IsTiled then WriteString(ahmsctiledwall, InttoStr(1))
               else WriteString(ahmsctiledwall, InttoStr(0));
    StrPCopy(PasFileName,FileName);
    if not(SystemParametersInfo( SPI_SetDeskWallPaper, 1,@PasFileName, SPIF_UPDATEINIFILE )) then showmessage('sadas');
    WriteString(ahmscwallpaper,FileName);
    CloseKey;
  finally
    Free;
  end;
end;

constructor TAHMWinWallPaper.create;
begin
  inherited Create;
  FTiled:=True;
end;

function TAHMWinWallPaper.Execute: Boolean;
begin
  AHMSetWallPaper(FFileName,FTiled);
  result:=true;
end;

function TAHMSystemManager.SetWallPaper: Boolean;
begin
  Result:=FWallpaper.Execute;
end;

Function DoMinimizeAll(Handle:HWnd;lparam :DWord) : Boolean; stdcall;
var WindowName  : Array[0..255] of Char;
    CApplicationName : Array[0..255] of Char;
    CClassName : Array[0..255] of Char;
    EnumFormsFnd : Boolean;
    EForms : Integer;
begin
  DoMinimizeAll:=True;
  EnumFormsFnd:=False;
  For EForms:=0 to Screen.Formcount-1 do
  if Screen.Forms[EFOrms].Handle=Handle then EnumFormsFnd:=True;
  GetWindowText(Application.Handle,CApplicationName, SizeOf(CApplicationName));
  GetClassName(Application.Handle, CClassName, SizeOf(CClassName));
  if not(enumformsfnd) then
  if GetWindowText(Handle, WindowName, SizeOf(WindowName)) > 0 then
  if StrComp(WindowName, CApplicationName) <> 0 then
  if IsWindowVisible(Handle) then
  if Handle<>LParam then
  if IsWindow(GetLastActivePopup(Handle)) then
  if Handle=GetLastActivePopup(Handle) then
  if IsWindow(Handle) then
  if not IsChild(Application.Handle,Handle) then
  begin
    SetWindowPos(Handle, HWND_TOP,0,0,0,0,SWP_NOZORDER+SWP_NOMOVE+SWP_NOSIZE+SWP_HideWindow);
    SendMessage(Handle,WM_SYSCOMMAND,SC_Minimize,0);
    SetWindowPos(Handle, HWND_TOP,0,0,0,0,SWP_NOZORDER+SWP_NOMOVE+SWP_NOSIZE+SWP_SHOWWINDOW)
  end;
end;

Function MinimizeAllWindows : Boolean;
begin
  if Application.Mainform<>nil then
    result:=EnumWindows(@DoMinimizeAll,Application.MainForm.Handle)
  else
    result:=EnumWindows(@DoMinimizeAll,Application.Handle);
end;

{ TAHMSystemOptions }
constructor TAHMSystemOptions.Create(AOwner : TAHMSystemManager);
begin
  inherited Create;
  FAHMSystemManager:=AOwner;
  FMinimizeAll:=False;
  FWinIcons:=True;
  FWinTaskBar:=True;
  FWinOfficeBar:=True;
end;

Destructor TAHMSystemOptions.Destroy;
begin
  inherited Destroy;
end;

function TAHMSystemOptions.pGetWinAnimation: Boolean;
Var AnimationInfo : TAnimationInfo;
begin
  FillChar(AnimationInfo,SizeOf(AnimationInfo),0);
  AnimationInfo.cbSize := sizeof (TAnimationInfo);
  SystemParametersInfo(SPI_GETANIMATION, SizeOf(TAnimationInfo), @AnimationInfo,0);
  result:=(AnimationInfo.iMinAnimate<>0);
end;

procedure TAHMSystemOptions.SetWinAnimation(const Value: Boolean);
Var AnimationInfo : TAnimationInfo;
begin
  FillChar(AnimationInfo,SizeOf(AnimationInfo),0);
  AnimationInfo.cbSize := sizeof (TAnimationInfo);
  if Value then AnimationInfo.iMinAnimate := 1 else AnimationInfo.iMinAnimate := 0;
  SystemParametersInfo(SPI_SETANIMATION, SizeOf(TAnimationInfo), @AnimationInfo, SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE);
end;

function TAHMSystemOptions.pGetWinDragFull: Boolean;
begin
  SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, @result,0);
end;

procedure TAHMSystemOptions.SetWinDragFull(const Value: Boolean);
begin
  SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, LongInt(Value),nil,SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE);
end;


function TAHMSystemOptions.GetFontSmoothing: Boolean;
begin
  SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, @result,0);
end;

function TAHMSystemOptions.GetWarningBeep: Boolean;
begin
  SystemParametersInfo(SPI_GETBEEP, 0, @result,0);
end;

procedure TAHMSystemOptions.SetFontSmoothing(const Value: Boolean);
begin
  SystemParametersInfo(SPI_SETFONTSMOOTHING,LongInt(Value),nil,SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE);
end;

procedure TAHMSystemOptions.SetWarningbeep(const Value: Boolean);
begin
  SystemParametersInfo(SPI_SETBEEP, LongInt(Value),nil,SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE);
end;

function TAHMSystemOptions.GetSnapToDefaultBtn: Boolean;
begin
  SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0, @result,0);
end;

procedure TAHMSystemOptions.SetSnapToDefaultBtn(const Value: Boolean);
begin
  if AHMIsWinNT then
   SystemParametersInfo(SPI_SETSNAPTODEFBUTTON, LongInt(Value),nil,SPIF_UPDATEINIFILE or SPIF_SENDWININICHANGE);
end;

procedure TAHMSystemOptions.SetMinimizeAll(const Value: Boolean);
begin
  if Value then MinimizeAllWindows;
end;

procedure TAHMSystemOptions.SetWinTaskbar(const Value: Boolean);
begin
  FWinTaskBar := Value;
  FAHMSystemManager.DoHideWindow(PChar(ahmscwintray),Value);
end;

procedure TAHMSystemOptions.SetWinOfficeBar(const Value: Boolean);
begin
  FWinOfficeBar := Value;
  FAHMSystemManager.DoHideWindow(PChar(ahmscofficetray),Value);
end;

procedure TAHMSystemOptions.SetWinIcons(const Value: Boolean);
begin
  FWinIcons := Value;
  FAHMSystemManager.DoHideWindow(PChar(ahmscicons),Value);
end;

function TAHMSystemManager.DoHideWindow(ATaskName: Pchar; AVisible: Boolean): Boolean;
var ABar : THandle;
begin
 ABar:=FindWindow(ATaskName,nil);
  if ABar<>0 then result:=True else result:=False;
  if AVisible then
   SetWindowPos(ABar, HWND_TOP,0,0,0,0,SWP_NOZORDER+SWP_NOMOVE+SWP_NOSIZE+SWP_SHOWWINDOW)
  else
   SetWindowPos(ABar, HWND_TOP,0,0,0,0,SWP_NOZORDER+SWP_NOMOVE+SWP_NOSIZE+SWP_HideWindow);
end;

end.
