Delphi 防止系统睡眠


本文整理自网络,侵删。

 

Windows检测到诸如键盘或鼠标输入之类的活动?C长时间闲置后,系统可能会进入睡眠模式和/或关闭显示设备的电源。

这是您可以用来防止系统在关键操作期间进入休眠状态的单元。

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
    // Prevent the sleep idle time-out and Power off.
    SetThreadExecutionState(ES_SYSTEM_REQUIRED or ES_CONTINUOUS)
  else
    // Clear EXECUTION_STATE flags to disable away mode and allow the
    // system to idle to sleep normally.
    SetThreadExecutionState(ES_CONTINUOUS);
end;

initialization

SystemCritical := TSystemCritical.Create;

finalization

SystemCritical.IsCritical := False;
SystemCritical.Free;

end.
Here's one usage example:

SystemCritical.IsCritical = true;
try
  // do critical operation here
  // without going in to sleep or turning off the display
finally
  SystemCritical.IsCritical = false;
end;

相关阅读 >>

Delphi win7,win2008,win2003,winxp 屏蔽ctrl+alt+del

Delphi 测试字符串写入类: tstringwriter

Delphi编解码js字符串

Delphi判断电脑是否安装了excel

Delphi 获取中文/数字星期的函数

Delphi 获取\xxx\xxxx\1234最后一级名称

Delphi 打造mygetprocaddress函数(Delphi源码)

Delphi xe5开发android程序调用电话相关功能(短信息和电话)

Delphi 用 directshow 获取本机的视频摄像设备列表

Delphi 的字符串在 firemonkey 模式下

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...