分享

Delphi 操作Windows系统睡眠

 独孤求财 2021-04-29
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. 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多