if Application.MessageBox('确定關机?','確認關閉電腦',MB_YESNO )=IDYES then
begin
if RadioButton1.Checked=true then
ExitWindowsEx(EWX_LOGOFF,0) //以其他用戶身份登錄
else if RadioButton2.Checked=true then
ExitWindowsEx(EWX_SHUTDOWN,1) //安全關机
else if RadioButton3.Checked=true then
ExitWindowsEx(EWX_REBOOT,2) //重新啟動計算机
else if RadioButton4.Checked=true then
ExitWindowsEx(EWX_FORCE,4) //強行關机
else if RadioButton5.Checked=true then
ExitWindowsEx(EWX_POWEROFF,8); //關閉係統並關閉電源
end;
procedure tform1.ShutDown;
procedure AdjustToken(); //获取关机控制权
var
hdlProcessHandle, hdlTokenHandle, lBufferNeeded: Cardinal;
tmpLuid: Int64;
//tkpPrivilegeCount: Int64;
tkp, tkpNewButIgnored: TOKEN_PRIVILEGES;
Privilege: array[0..0] of _LUID_AND_ATTRIBUTES;
begin
hdlProcessHandle := GetCurrentProcess;
OpenProcessToken(hdlProcessHandle,
(TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY),
hdlTokenHandle);
// Get the LUID for shutdown privilege.
LookupPrivilegeValue('', 'SeShutdownPrivilege', tmpLuid);
Privilege[0].Luid := tmpLuid;
Privilege[0].Attributes := SE_PRIVILEGE_ENABLED;
tkp.PrivilegeCount := 1; // One privilege to set
tkp.Privileges[0] := Privilege[0];
// Enable the shutdown privilege in the access token of this process.
AdjustTokenPrivileges(hdlTokenHandle,
False,
tkp,
Sizeof(tkpNewButIgnored),
tkpNewButIgnored,
lBufferNeeded);
end;
begin
AdjustToken;
case send of
1: ExitWindowsEx(EWX_FORCE, 0); //在紧急情况下强制关机。 ;
2: ExitWindowsEx(EWX_LOGOFF, 0); //以其他用户身份登录。 ;
3: ExitWindowsEx(EWX_POWEROFF, 0); //关闭系统并关闭电源。
4: if application.MessageBox('是否重新启动', '重启计算机提示框', 1+48)=1 then //idok
begin
showmessage('reboot');
ExitWindowsEx(EWX_REBOOT, $FFFF); //重启操作系统
end
else
exit;
5: if application.MessageBox('是否关闭', '关闭计算机提示框', 1+48)=1 then //idok
begin
showmessage('close');
ExitWindowsEx(EWX_SHUTDOWN, $FFFF); //关机;
end
else
exit;
else
EXIT;
end;
end;
调用方法如下:
procedure TForm1.Button1Click(Sender: TObject);
begin
send:=3;
ShutDown;
end;
这篇博客介绍了如何使用DELPHI通过Radiobutton选择不同的操作,实现计算机的关机、重新启动、安全关机和强制关机。核心代码涉及到ExitWindowsEx函数的调用,并通过AdjustToken()过程获取关机控制权。

被折叠的 条评论
为什么被折叠?



