Delphi实现强制关机(适用于各个Win系统)

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
    function GetOperatingSystem(): string;
    procedure ShutDownComputer();
    procedure Get_Shutdown_Privilege();
var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShutDownComputer();
end;

procedure ShutDownComputer();
begin
  if GetOperatingSystem() = 'Windows NT/2000/XP' then
  begin
    Get_Shutdown_Privilege();
    //调用此函数会出现系统关机提示窗口,并允许用户取消关机动作
    InitiateSystemShutDown(nil, '关机提示:讨厌你所以关了你!', 3, True, False);
    // InitiateSystemShutDown去掉的话就不显示提示窗口
    ExitWindowsEx(EWX_SHUTDOWN+EWX_FORCE+EWX_POWEROFF+EWX_FORCEIFHUNG,0);
  end
  else
  begin
    ExitWindowsEx(EWX_SHUTDOWN+EWX_FORCE+EWX_POWEROFF+EWX_FORCEIFHUNG,0);
  end;
end;

function GetOperatingSystem(): string; //获取操作系统信息
var
  osVerInfo: TOSVersionInfo;

begin
  Result:= '';
  osVerInfo.dwOSVersionInfoSize:= SizeOf(TOSVersionInfo);

  if GetVersionEx(osVerInfo) then
    case osVerInfo.dwPlatformId of
    VER_PLATFORM_WIN32_NT:
      begin
        Result:= 'Windows NT/2000/XP'
      end;
    VER_PLATFORM_WIN32_WINDOWS:
      begin
        Result := 'Windows 95/98/98SE/Me';
      end;
  end;
end;

procedure Get_Shutdown_Privilege(); //获得用户关机特权,仅对Windows NT/2000/XP
var   
  rl: Cardinal;  
  hToken: Cardinal;  
  tkp: TOKEN_PRIVILEGES;   
begin
  OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);

  if LookupPrivilegeValue(nil, 'SeShutdownPrivilege', tkp.Privileges[0].Luid) then
  begin  
    tkp.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
    tkp.PrivilegeCount:= 1;
    AdjustTokenPrivileges(hToken, False, tkp, 0, nil, rl);  
  end;  
end;

end.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值