Auto Shutdown Windows lazarus / 34-Windows ---------------------------------------------------------------------- j0x · 2012-03-10 12:20 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 · 2012-03-10 13:35 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 · 2012-03-10 20:26 Too lazy to extract, just take the one you need from attached source EDIT: attachment was missing ---------------------------------------------------------------------- DirkS · 2012-03-10 20:50 Quote from: Leledumbo on March 10, 2012, 09:26:18 pmToo lazy to extract, just take the one you need from attached source Which source? ---------------------------------------------------------------------- j0x · 2012-03-16 04:11 thanks folks im gonna look at the links you all provided when i got time again ---------------------------------------------------------------------- j0x · 2012-03-17 23:59 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 · 2013-03-07 19:57 Quote from: Leledumbo on March 10, 2012, 09:26:18 pmToo 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. ---------------------------------------------------------------------- Leledumbo · 2013-03-08 00:15 QuoteYour code does not workHave you even tried it? It works on my XP, and a reply above you confirms so. Quotewhere is allocating memory for hToken and TokenPriv. If count of preveleges is 2 or more LookupPrivilegeValue writes data on hTokenFeel 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 · 2013-03-08 13:18 I've attached project , which give error. ---------------------------------------------------------------------- Leledumbo · 2013-03-08 13:39 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 · 2013-03-08 14:44 Quote from: Leledumbo on March 08, 2013, 02:39:02 pm...feel free to fix the code (or wait for someone else to do so). Not fix, but completely rewrite . See attachment. ---------------------------------------------------------------------- anna · 2013-03-09 18:04 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 . ---------------------------------------------------------------------- anna · 2013-03-09 18:55 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;" ---------------------------------------------------------------------- RAW · 2018-09-15 18:52 I like to use this on WXP SP3 x86 and W7 SP1 x64. UNIT Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i UNIT ExitWinNT;{$MODE OBJFPC}{$H+} Interface USES  Windows, SysUtils;  CONST  LogOff   = EWX_LOGOFF   Or EWX_FORCEIFHUNG;  StandBy  = EWX_POWEROFF Or EWX_FORCEIFHUNG;  ReBoot   = EWX_REBOOT;   //Or EWX_FORCEIFHUNG;  ShutDown = EWX_SHUTDOWN; //Or EWX_FORCEIFHUNG;   ForceLogOff   = EWX_LOGOFF   Or EWX_FORCE;  ForceStandBy  = EWX_POWEROFF Or EWX_FORCE;  ForceReBoot   = EWX_REBOOT   Or EWX_FORCE;  ForceShutDown = EWX_SHUTDOWN Or EWX_FORCE;   Function ExitWin(lwParam: LongWord): Boolean; Implementation  Function ExitWin(lwParam: LongWord): Boolean;Var hToken  : THandle; TP,TPx  : TTokenPrivileges; dwTPrev : DWORD; dwTPReq : DWORD; booToken: Boolean;Const ShutDownName = 'SeShutdownPrivilege';Begin  Result:= False;   If Win32Platform = VER_PLATFORM_WIN32_NT  Then   Begin    booToken:= OpenProcessToken(GetCurrentProcess(),     TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken);     If booToken    Then     Begin      booToken:= LookupPrivilegeValue       (Nil, ShutDownName, TP.Privileges[0].LuID);       TP.PrivilegeCount:= 1;    TP.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;      dwTPrev:= SizeOf(TPx);      dwTPReq:= 0;       If booToken      Then       Begin        Windows.AdjustTokenPrivileges         (hToken, False, TP, dwTPrev, TPx, dwTPReq);         If ExitWindowsEx(lwParam, 0)      Then Result:= True;         CloseHandle(hToken);       End;     End;   End;End; END. Example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1;{$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, StdCtrls; type  TForm1 = class(TForm)    Button1: TButton;  Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private   public   end; var  Form1: TForm1; implementationuses ExitWinNT;{$R *.lfm} procedure TForm1.Button1Click(Sender: TObject);begin  ExitWin(Reboot);end; procedure TForm1.Button2Click(Sender: TObject);begin  ExitWin(ShutDown);end; end. Or this LPR if I want two exe files with a quicklaunch icon on the right bottom of the taskbar... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i PROGRAM project1; USES Windows, SysUtils; CONST  LogOff   = EWX_LOGOFF   Or EWX_FORCEIFHUNG;  StandBy  = EWX_POWEROFF Or EWX_FORCEIFHUNG;  ReBoot = EWX_REBOOT;   //Or EWX_FORCEIFHUNG;  ShutDown = EWX_SHUTDOWN; //Or EWX_FORCEIFHUNG;   ForceLogOff   = EWX_LOGOFF   Or EWX_FORCE;  ForceStandBy  = EWX_POWEROFF Or EWX_FORCE;  ForceReBoot   = EWX_REBOOT   Or EWX_FORCE;  ForceShutDown = EWX_SHUTDOWN Or EWX_FORCE;  Function ExitWin(lwParam: LongWord): Boolean;Var hToken  : THandle; TP,TPx  : TTokenPrivileges; dwTPrev : DWORD; dwTPReq : DWORD; booToken: Boolean;Const ShutDownName = 'SeShutdownPrivilege';Begin  Result:= False;   If Win32Platform = VER_PLATFORM_WIN32_NT  Then   Begin    booToken:= OpenProcessToken(GetCurrentProcess(),     TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken);     If booToken    Then     Begin      booToken:= LookupPrivilegeValue       (Nil, ShutDownName, TP.Privileges[0].LuID);       TP.PrivilegeCount:= 1;    TP.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;      dwTPrev:= SizeOf(TPx);      dwTPReq:= 0;       If booToken      Then       Begin        Windows.AdjustTokenPrivileges         (hToken, False, TP, dwTPrev, TPx, dwTPReq);         If ExitWindowsEx(lwParam, 0)      Then Result:= True;         CloseHandle(hToken);       End;     End;   End;End; BEGIN  ExitWin(ReBoot);END. ---------------------------------------------------------------------- kinlion · 2018-12-13 06:17 I think it's better to use Windows' shell cmd  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses UTF8Process; procedure shutdownSystem;begin  RunCmdFromPath('shutdown', '/p /f');  // RunCmdFromPath is in the unit UTF8Processend; I have used it in my project. It works in both Win7 and Win10. ---------------------------------------------------------------------- CCRDude · 2018-12-13 06:33 @kinlion: it's nice that you found an alternate way, but why do you think it would be better to use? Direct API usage allows to interpret possible error reasons at a fine level, while your example, well, runs. You can't evaluate if its failing because a driver blocks the reboot, or shutdown is prohibited for your privileges, or ... ---------------------------------------------------------------------- kinlion · 2018-12-14 09:20 Quote from: CCRDude on December 13, 2018, 07:33:18 am@kinlion: it's nice that you found an alternate way, but why do you think it would be better to use? Direct API usage allows to interpret possible error reasons at a fine level, while your example, well, runs. You can't evaluate if its failing because a driver blocks the reboot, or shutdown is prohibited for your privileges, or ... OK. I just feel the code is simple