Desligando e Reiniciando o Windows

 

Nesta dica veremos como desligar e reiniciar o Windows. Os passos necessários para implementá-lo são os seguintes:

1) Inclua no seu formulário dois componentes do tipo Button;

2) Escreva o código a seguir, de forma que a sua Unit se pareça com o texto abaixo:

 

unit Unit1;

 

interface

 

uses

    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

    Dialogs, StdCtrls;

 

type

    TForm1 = class(TForm)

        Button1: TButton;

        Button2: TButton;

        procedure Button1Click(Sender: TObject);

        procedure Button2Click(Sender: TObject);

    private

        { Private declarations }

        Function DesligarMeuWindows(RebootParam: Longword): Boolean;

    public

        { Public declarations }

    end;

 

var

    Form1: TForm1;

 

implementation

 

{$R *.dfm}

 

{ TForm1 }

 

function TForm1.DesligarMeuWindows(RebootParam: Longword): Boolean;

var

    TTokenHd: THandle;

    TTokenPvg: TTokenPrivileges;

    cbtpPrevious: DWORD;

    rTTokenPvg: TTokenPrivileges;

    pcbtpPreviousRequired: DWORD;

    tpResult: Boolean;

const

    SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';

begin

    if Win32Platform = VER_PLATFORM_WIN32_NT then

    begin

        tpResult := OpenProcessToken(GetCurrentProcess(),

            TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,

            TTokenHd);

        if tpResult then

        begin

            tpResult := LookupPrivilegeValue(nil, SE_SHUTDOWN_NAME, TTokenPvg.Privileges[0].Luid);

            TTokenPvg.PrivilegeCount := 1;

            TTokenPvg.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;

            cbtpPrevious := SizeOf(rTTokenPvg);

            pcbtpPreviousRequired := 0;

            if tpResult then

                Windows.AdjustTokenPrivileges(TTokenHd, False, TTokenPvg, cbtpPrevious, rTTokenPvg, pcbtpPreviousRequired);

        end;

    end;

    Result := ExitWindowsEx(RebootParam, 0);

end;

 

procedure TForm1.Button1Click(Sender: TObject);

begin

    DesligarMeuWindows(EWX_POWEROFF or EWX_FORCE);

end;

 

procedure TForm1.Button2Click(Sender: TObject);

begin

    DesligarMeuWindows(EWX_REBOOT or EWX_FORCE);

end;

 

end.

 

por Edison Costa

webmaster@clubedelphi.net