Fork me on GitHub

C# 代码实现关机

AdvApi32.LookupPrivilegeValue(null, "SeShutdownPrivilege", out var lpLuid);

using var t = AdvApi32.SafeHTOKEN.FromThread(Kernel32.SafeHTHREAD.Current,
AdvApi32.TokenAccess.TOKEN_ADJUST_PRIVILEGES | AdvApi32.TokenAccess.TOKEN_QUERY);

var ptp = new AdvApi32.TOKEN_PRIVILEGES(luid:lpLuid, AdvApi32.PrivilegeAttributes.SE_PRIVILEGE_ENABLED);

AdvApi32.AdjustTokenPrivileges(t,false,ptp,out var old);
User32.ExitWindowsEx(User32.ExitWindowsFlags.EWX_POWEROFF | User32.ExitWindowsFlags.EWX_FORCE,
          SystemShutDownReason.SHTDN_REASON_MAJOR_NONE);

需要在nuget上下载:
Vanara.PInvoke.Kernel32
Vanara.PInvoke.User32
Vanara.PInvoke.Security

posted @ 2023-05-30 11:07  芝麻科技  阅读(190)  评论(2编辑  收藏  举报
SesameTech