Recent

Author Topic: Auto Shutdown Windows  (Read 16659 times)

j0x

  • Full Member
  • ***
  • Posts: 126
Auto Shutdown Windows
« on: March 10, 2012, 01:20:16 pm »
i have this little program here -> http://code.google.com/p/cyko/downloads/list

and someone is requesting i add a auto shutdown when finish encoding feature so do anyone know how to do this?

thanks

User137

  • Hero Member
  • *****
  • Posts: 1790
    • Nxpascal home
Re: Auto Shutdown Windows
« Reply #1 on: March 10, 2012, 02:35:29 pm »
Just giving out some tips, Google search with "winapi windows shutdown"

http://www.techrepublic.com/article/programmatically-shut-down-a-windows-machine-with-this-api/5030366

Can't say that WinAPI commands can always be count on just like that. There may be differences between Windows versions or sometimes even 32/64 bit.

Leledumbo

  • Hero Member
  • *****
  • Posts: 8089
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: Auto Shutdown Windows
« Reply #2 on: March 10, 2012, 09:26:18 pm »
Too lazy to extract, just take the one you need from attached source
EDIT: attachment was missing
« Last Edit: March 11, 2012, 06:18:30 am by Leledumbo »

DirkS

  • Sr. Member
  • ****
  • Posts: 251
Re: Auto Shutdown Windows
« Reply #3 on: March 10, 2012, 09:50:19 pm »
Too lazy to extract, just take the one you need from attached source
Which source?

j0x

  • Full Member
  • ***
  • Posts: 126
Re: Auto Shutdown Windows
« Reply #4 on: March 16, 2012, 05:11:26 am »
thanks folks im gonna look at the links you all provided when i got time again  :)

j0x

  • Full Member
  • ***
  • Posts: 126
Re: Auto Shutdown Windows
« Reply #5 on: March 18, 2012, 12:59:23 am »
thanks Leledumbo it works, i use the following codes, mostly just copy and pasted it though
Code: [Select]
uses
  SysUtils, Windows;

const
  SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege';
  SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege';
  SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege';
  SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege';
  SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege';
  SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege';
  SE_TCB_NAME = 'SeTcbPrivilege';
  SE_SECURITY_NAME = 'SeSecurityPrivilege';
  SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege';
  SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege';
  SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege';
  SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege';
  SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege';
  SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege';
  SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege';
  SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege';
  SE_BACKUP_NAME = 'SeBackupPrivilege';
  SE_RESTORE_NAME = 'SeRestorePrivilege';
  SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
  SE_DEBUG_NAME = 'SeDebugPrivilege';
  SE_AUDIT_NAME = 'SeAuditPrivilege';
  SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege';
  SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege';
  SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege';
  SE_UNDOCK_NAME = 'SeUndockPrivilege';
  SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege';
  SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege';
  SE_MANAGE_VOLUME_NAME = 'SeManageVolumePrivilege';

function SetSuspendState(hibernate, forcecritical, disablewakeevent: Boolean): Boolean; stdcall; external 'powrprof.dll' name 'SetSuspendState';
function IsHibernateAllowed: Boolean; stdcall; external 'powrprof.dll' name 'IsPwrHibernateAllowed';
function IsPwrSuspendAllowed: Boolean; stdcall; external 'powrprof.dll' name 'IsPwrSuspendAllowed';
function IsPwrShutdownAllowed: Boolean; stdcall; external 'powrprof.dll' name 'IsPwrShutdownAllowed';
function LockWorkStation: Boolean; stdcall; external 'user32.dll' name 'LockWorkStation';

implementation

function NTSetPrivilege(sPrivilege: string; bEnabled: Boolean): Boolean;
var
  hToken: THandle;
  TokenPriv: TOKEN_PRIVILEGES;
  PrevTokenPriv: TOKEN_PRIVILEGES;
  ReturnLength: Cardinal;
begin
  Result := True;
  // Only for Windows NT/2000/XP and later.
  if not (Win32Platform = VER_PLATFORM_WIN32_NT) then Exit;
  Result := False;

  // obtain the processes token
  if OpenProcessToken(GetCurrentProcess(),
    TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then
  begin
    try
      // Get the locally unique identifier (LUID) .
      if LookupPrivilegeValue(nil, PChar(sPrivilege),
        TokenPriv.Privileges[0].Luid) then
      begin
        TokenPriv.PrivilegeCount := 1; // one privilege to set

        case bEnabled of
          True: TokenPriv.Privileges[0].Attributes  := SE_PRIVILEGE_ENABLED;
          False: TokenPriv.Privileges[0].Attributes := 0;
        end;

        ReturnLength := 0; // replaces a var parameter
        PrevTokenPriv := TokenPriv;

        // enable or disable the privilege

        AdjustTokenPrivileges(hToken, False, TokenPriv, SizeOf(PrevTokenPriv),
          PrevTokenPriv, ReturnLength);
      end;
    finally
      CloseHandle(hToken);
    end;
  end;
  // test the return value of AdjustTokenPrivileges.
  Result := GetLastError = ERROR_SUCCESS;
  if not Result then
    raise Exception.Create(SysErrorMessage(GetLastError));
end;                                 

procedure TfrmMain.tmrEncodeTimer(Sender: TObject);
// **other codes in here **
if chkShutdown.Checked = True then
      begin
        NTSetPrivilege(SE_SHUTDOWN_NAME, True);
        ExitWindowsEx(EWX_SHUTDOWN or EWX_FORCE, 0);
      end;   
end;

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: Auto Shutdown Windows
« Reply #6 on: March 07, 2013, 08:57:13 pm »
Too lazy to extract, just take the one you need from attached source
EDIT: attachment was missing
Your code does not work. Reason: where is allocating memory for hToken and TokenPriv .
 If count of preveleges is 2 or more LookupPrivilegeValue writes data on hToken.
« Last Edit: March 07, 2013, 09:17:02 pm by theo »
WinXP SP3 Pro Russian 32-bit (5.1.2600)

Leledumbo

  • Hero Member
  • *****
  • Posts: 8089
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: Auto Shutdown Windows
« Reply #7 on: March 08, 2013, 01:15:11 am »
Quote
Your code does not work
Have you even tried it? It works on my XP, and a reply above you confirms so.
Quote
where is allocating memory for hToken and TokenPriv.
If count of preveleges is 2 or more LookupPrivilegeValue writes data on hToken
Feel free to fix the code, I don't need PrivilegeCount more than 1 (it's not required to do all functionalities required in the program).

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: Auto Shutdown Windows
« Reply #8 on: March 08, 2013, 02:18:13 pm »
I've attached project , which give error.
WinXP SP3 Pro Russian 32-bit (5.1.2600)

Leledumbo

  • Hero Member
  • *****
  • Posts: 8089
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: Auto Shutdown Windows
« Reply #9 on: March 08, 2013, 02:39:02 pm »
I don't use Windows anymore, so I can't help. And as I said earlier, feel free to fix the code (or wait for someone else to do so).

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: Auto Shutdown Windows
« Reply #10 on: March 08, 2013, 03:44:28 pm »
...feel free to fix the code (or wait for someone else to do so).
Not fix, but completely rewrite . See attachment.
WinXP SP3 Pro Russian 32-bit (5.1.2600)

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: Auto Shutdown Windows
« Reply #11 on: March 09, 2013, 07:04:25 pm »
 What is difference between EWX_SHUTDOWN and EWX_POWEROFF ? Microsoft says , that EWX_SHUTDOWN just closes all processes and gives a message, that computer is ready to take plug away. So why you named PowerOff as 'Soft Power Off '? PowerOff procedure will forced terminate all processes and switch motherboard power off .
WinXP SP3 Pro Russian 32-bit (5.1.2600)

anna

  • Sr. Member
  • ****
  • Posts: 426
Re: Auto Shutdown Windows
« Reply #12 on: March 09, 2013, 07:55:13 pm »
I have tested taskmgr.exe. It has a Turn Off option :
http://img823.imageshack.us/img823/2773/71126471.png

I open my debugger and put conditional breakpoint on TranslateMessage MSG=111 (WM_COMMAND). Then I trace a little and . Well if you just hit Turn Off , taskmgr will call ExitWindowsEx(EWX_POWEROFF,0).
As microsoft says , if secong parameter will be zero, windows state data will be written on some file, which can delay shutdown. Therefore, it's not recommended.
But very interesting if you hit Turn Off with Ctrl key pressed. Then taskmgr call NtShutdownSystem(2). NtShutdownSystem = ZwShutdownSystem

____

For Hibernate taskmgr  uses ntdll.NtInitiatePowerAction (3,2,3,0)
3 = PowerActionHibernate
2 = PowerSystemSleeping1
3 = POWER_ACTION_QUERY_ALLOWED or POWER_ACTION_UI_ALLOWED
0 = routine does not return immediately


Note, that taskmgr creates new thread and  doing power operation  inside thread.

____
You can use Nt-procedures by adding "uses jwaNative;"
« Last Edit: March 10, 2013, 04:38:57 pm by anna »
WinXP SP3 Pro Russian 32-bit (5.1.2600)

RAW

  • Hero Member
  • *****
  • Posts: 781
Re: Auto Shutdown Windows
« Reply #13 on: September 15, 2018, 08:52:25 pm »
I like to use this on WXP SP3 x86 and W7 SP1 x64.

UNIT
Code: Pascal  [Select]
  1. UNIT ExitWinNT;
  2. {$MODE OBJFPC}{$H+}
  3.  
  4. Interface
  5.  USES
  6.   Windows, SysUtils;
  7.  
  8.  CONST
  9.   LogOff   = EWX_LOGOFF   Or EWX_FORCEIFHUNG;
  10.   StandBy  = EWX_POWEROFF Or EWX_FORCEIFHUNG;
  11.   ReBoot   = EWX_REBOOT;   //Or EWX_FORCEIFHUNG;
  12.   ShutDown = EWX_SHUTDOWN; //Or EWX_FORCEIFHUNG;
  13.  
  14.   ForceLogOff   = EWX_LOGOFF   Or EWX_FORCE;
  15.   ForceStandBy  = EWX_POWEROFF Or EWX_FORCE;
  16.   ForceReBoot   = EWX_REBOOT   Or EWX_FORCE;
  17.   ForceShutDown = EWX_SHUTDOWN Or EWX_FORCE;
  18.  
  19.   Function ExitWin(lwParam: LongWord): Boolean;
  20.  
  21. Implementation
  22.  
  23.  
  24. Function ExitWin(lwParam: LongWord): Boolean;
  25. Var
  26.  hToken  : THandle;
  27.  TP,TPx  : TTokenPrivileges;
  28.  dwTPrev : DWORD;
  29.  dwTPReq : DWORD;
  30.  booToken: Boolean;
  31. Const
  32.  ShutDownName = 'SeShutdownPrivilege';
  33. Begin
  34.   Result:= False;
  35.  
  36.   If Win32Platform = VER_PLATFORM_WIN32_NT
  37.   Then
  38.    Begin
  39.     booToken:= OpenProcessToken(GetCurrentProcess(),
  40.      TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken);
  41.  
  42.     If booToken
  43.     Then
  44.      Begin
  45.       booToken:= LookupPrivilegeValue
  46.        (Nil, ShutDownName, TP.Privileges[0].LuID);
  47.  
  48.       TP.PrivilegeCount:= 1;
  49.       TP.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  50.       dwTPrev:= SizeOf(TPx);
  51.       dwTPReq:= 0;
  52.  
  53.       If booToken
  54.       Then
  55.        Begin
  56.         Windows.AdjustTokenPrivileges
  57.          (hToken, False, TP, dwTPrev, TPx, dwTPReq);
  58.  
  59.         If ExitWindowsEx(lwParam, 0)
  60.         Then Result:= True;
  61.  
  62.         CloseHandle(hToken);
  63.        End;
  64.      End;
  65.    End;
  66. End;
  67.  
  68. END.


Example:
Code: Pascal  [Select]
  1. unit Unit1;
  2. {$mode objfpc}{$H+}
  3.  
  4. interface
  5.  
  6. uses
  7.   Classes, SysUtils, Forms, Controls, StdCtrls;
  8.  
  9. type
  10.   TForm1 = class(TForm)
  11.     Button1: TButton;
  12.     Button2: TButton;
  13.     procedure Button1Click(Sender: TObject);
  14.     procedure Button2Click(Sender: TObject);
  15.   private
  16.  
  17.   public
  18.  
  19.   end;
  20.  
  21. var
  22.   Form1: TForm1;
  23.  
  24. implementation
  25. uses ExitWinNT;
  26. {$R *.lfm}
  27.  
  28. procedure TForm1.Button1Click(Sender: TObject);
  29. begin
  30.   ExitWin(Reboot);
  31. end;
  32.  
  33. procedure TForm1.Button2Click(Sender: TObject);
  34. begin
  35.   ExitWin(ShutDown);
  36. end;
  37.  
  38. end.


Or this LPR if I want two exe files with a quicklaunch icon on the right bottom of the taskbar...
Code: Pascal  [Select]
  1. PROGRAM project1;
  2.  
  3. USES
  4.  Windows, SysUtils;
  5.  
  6. CONST
  7.   LogOff   = EWX_LOGOFF   Or EWX_FORCEIFHUNG;
  8.   StandBy  = EWX_POWEROFF Or EWX_FORCEIFHUNG;
  9.   ReBoot   = EWX_REBOOT;   //Or EWX_FORCEIFHUNG;
  10.   ShutDown = EWX_SHUTDOWN; //Or EWX_FORCEIFHUNG;
  11.  
  12.   ForceLogOff   = EWX_LOGOFF   Or EWX_FORCE;
  13.   ForceStandBy  = EWX_POWEROFF Or EWX_FORCE;
  14.   ForceReBoot   = EWX_REBOOT   Or EWX_FORCE;
  15.   ForceShutDown = EWX_SHUTDOWN Or EWX_FORCE;
  16.  
  17.  
  18. Function ExitWin(lwParam: LongWord): Boolean;
  19. Var
  20.  hToken  : THandle;
  21.  TP,TPx  : TTokenPrivileges;
  22.  dwTPrev : DWORD;
  23.  dwTPReq : DWORD;
  24.  booToken: Boolean;
  25. Const
  26.  ShutDownName = 'SeShutdownPrivilege';
  27. Begin
  28.   Result:= False;
  29.  
  30.   If Win32Platform = VER_PLATFORM_WIN32_NT
  31.   Then
  32.    Begin
  33.     booToken:= OpenProcessToken(GetCurrentProcess(),
  34.      TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken);
  35.  
  36.     If booToken
  37.     Then
  38.      Begin
  39.       booToken:= LookupPrivilegeValue
  40.        (Nil, ShutDownName, TP.Privileges[0].LuID);
  41.  
  42.       TP.PrivilegeCount:= 1;
  43.       TP.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
  44.       dwTPrev:= SizeOf(TPx);
  45.       dwTPReq:= 0;
  46.  
  47.       If booToken
  48.       Then
  49.        Begin
  50.         Windows.AdjustTokenPrivileges
  51.          (hToken, False, TP, dwTPrev, TPx, dwTPReq);
  52.  
  53.         If ExitWindowsEx(lwParam, 0)
  54.         Then Result:= True;
  55.  
  56.         CloseHandle(hToken);
  57.        End;
  58.      End;
  59.    End;
  60. End;
  61.  
  62. BEGIN
  63.   ExitWin(ReBoot);
  64. END.
Windows 7 Pro (x64 Sp1) And Windows XP Pro (x86 Sp3) - LAZARUS 2.0.4 FPC 3.0.4 - TRUNK 2.1.0 FPC 3.3.1

kinlion

  • New member
  • *
  • Posts: 45
  • I Love Lazarus
Re: Auto Shutdown Windows
« Reply #14 on: December 13, 2018, 07:17:33 am »
I think it's better to use Windows' shell cmd  :)
Code: Pascal  [Select]
  1. uses UTF8Process;
  2.  
  3. procedure shutdownSystem;
  4. begin
  5.   RunCmdFromPath('shutdown', '/p /f');  // RunCmdFromPath is in the unit UTF8Process
  6. end;

I have used it in my project. It works in both Win7 and Win10.
Lazarus 1.8.4 / FPC 3.0.4 / SVN 57972
On Win10 X64, have to compile for Win32