delphi 调用ExitWindows 关闭系统


本文整理自网络,侵删。

 
type
  TShutdownAction = (saLogoff, saReboot, saPoweroff);
 
function Shutdown(Action: TShutdownAction; AForce: Boolean): Boolean;
  function EnableShutdownPrivilege: Boolean;
  var
    hProcess, hToken: THandle;
    priv, lastpriv: TOKEN_PRIVILEGES;
    lastlen: Cardinal;
  const
    SE_SHUTDOWN_NAME: PWideChar = 'SeShutdownPrivilege';
  begin
    FillChar(priv, sizeof(priv), 0);
    FillChar(lastpriv, sizeof(priv), 0);
    hProcess := GetCurrentProcess;
    Result := False;
    if OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)
    then
    // 打开当前进程的访问令牌句柄(OpenProcessToken函数调用失败返回值为零)
    begin
      if LookupPrivilegeValue(nil, SE_SHUTDOWN_NAME, priv.Privileges[0].LUID)
      then
      begin
        priv.PrivilegeCount := 1; // 欲调整的权限个数
        priv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
        // 权限的属性,SE_PRIVILEGE_ENABLED为使能该权限
        if AdjustTokenPrivileges(hToken, False, priv, sizeof(priv), lastpriv,
          lastlen) then // 调整访问令牌里的指定权限(AdjustTokenPrivileges函数调用失败返回值为零)
          Result := GetLastError = ERROR_SUCCESS;
      end;
      CloseHandle(hToken);
    end;
  end;
 
var
  AFlags: Integer;
begin
  Result := EnableShutdownPrivilege;
  if Result then // 使能关机特权函数
  begin
    if AForce then
      AFlags := EWX_FORCE
    else
      AFlags := 0;
    case Action of
      saLogoff:
        AFlags := AFlags or EWX_LOGOFF;
      saReboot:
        AFlags := AFlags or EWX_REBOOT;
      saPoweroff:
        AFlags := AFlags or EWX_SHUTDOWN;
    end;
    Result := ExitWindowsEx(AFlags, 0) // 强制关机
  end;
end;

相关阅读 >>

Delphi idhttp控件学习(图片下载)

Delphi 程序启动窗体控制在桌面右下角

Delphi 实现无标题栏但有边框的窗口

Delphi issameday、istoday - 判断是不是同一天、判断是不是今天

Delphi多线程程序示例

Delphi 去掉ide开启后弹出安全警告框

Delphi xe5 json

Delphi 关于选择文件路径 selectdirectory 弹出窗口居中的问题

Delphi adoquery查询更改用户

Delphi流的操作

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



打赏

取消

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

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

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

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

评论

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