1. 程式人生 > 實用技巧 >Delphi 操作Windows系統睡眠-防止系統/電腦 進入睡眠或關閉顯示器

Delphi 操作Windows系統睡眠-防止系統/電腦 進入睡眠或關閉顯示器

Delphi 操作Windows系統睡眠-防止系統/電腦 進入睡眠或關閉顯示器

1、防止進入睡眠

1.1、引用單元

Delphi 單元:

unit SystemCriticalU;

interface

uses
  Windows;

type
  TSystemCritical = class
  private
    FIsCritical: Boolean;
    procedure SetIsCritical(const Value: Boolean) ;
  protected
    procedure UpdateCritical(Value: Boolean) ; virtual;
  public
    constructor Create;
    property IsCritical: Boolean read FIsCritical write SetIsCritical;
  end;

var
  SystemCritical: TSystemCritical;

implementation

{ TSystemCritical }
// REF: http://msdn.microsoft.com/en-us/library/aa373208.aspx
type
  EXECUTION_STATE = DWORD;
  
const
  ES_SYSTEM_REQUIRED = $00000001;
  ES_DISPLAY_REQUIRED = $00000002;
  ES_USER_PRESENT = $00000004;
  ES_AWAYMODE_REQUIRED = $00000040;
  ES_CONTINUOUS = $80000000;
  
  KernelDLL = 'kernel32.dll';

{
  SetThreadExecutionState Function
  Enables an application to inform the system that it is in use,
  thereby preventing the system from entering sleep or turning off the
  display while the application is running.
}
procedure SetThreadExecutionState(ESFlags: EXECUTION_STATE);
  stdcall; external kernel32 name 'SetThreadExecutionState';

constructor TSystemCritical.Create;
begin
  inherited;
  FIsCritical := False;
end;

procedure TSystemCritical.SetIsCritical(const Value: Boolean) ;
begin
  if FIsCritical = Value then
    Exit;
  FIsCritical := Value;
  UpdateCritical(FIsCritical);
end;

procedure TSystemCritical.UpdateCritical(Value: Boolean) ;
begin
  if Value then
    // 防止睡眠空閒超時和關機。
    SetThreadExecutionState(ES_SYSTEM_REQUIRED or ES_CONTINUOUS)
  else
    //清除執行狀態標誌以禁用離開模式並允許
    // 系統空閒以正常睡眠
    SetThreadExecutionState(ES_CONTINUOUS);
end;

initialization

SystemCritical := TSystemCritical.Create;

finalization

SystemCritical.IsCritical := False;
SystemCritical.Free;

end. 

引用示例:

SystemCritical.IsCritical = true;
try
  // 這裡做關鍵操作
  // 不會進入睡眠和關閉顯示器
finally
  SystemCritical.IsCritical = false;
end;

1.2 直接使用WinAPI函式,點選檢視:SetThreadExecutionState

 

2、使電腦進入睡眠

//提升程序令牌函式
function AdjustProcessPrivilege(ProcessHandle: THandle; Token_Name: Pchar): boolean;
var
  Token: THandle;
  TokenPri: _TOKEN_PRIVILEGES;
  ProcessDest: int64;
  l: DWORD;
begin
  Result := False;
  if OpenProcessToken(ProcessHandle, TOKEN_Adjust_Privileges, Token) then
  begin
    if LookupPrivilegeValue(nil, Token_Name, ProcessDest) then
    begin
      TokenPri.PrivilegeCount := 1;
      TokenPri.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
      TokenPri.Privileges[0].Luid := ProcessDest;
      l := 0;
      //更新程序令牌,成功返回TRUE
      if AdjustTokenPrivileges(Token, False, TokenPri, sizeof(TokenPri), nil, l) then
        Result := True;
    end;
  end;
end;  

引用示例:

if AdjustProcessPrivilege(GetCurrentProcess,'SeShutdownPrivilege') then//提升許可權
begin
  SetSystemPowerState(false,TRUE); //進入睡眠
end else begin
  //
end;

  

  

建立時間:2020.11.03  更新時間: