首先要导入对命名空间
usingSystem.Runtime.InteropServices;
的引用
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internalstructTokPRiv1Luid
{
publicintCount;
publiclongLuid;
publicintAttr;
}
[DllImport("kernel32.dll", ExactSpelling =true)]
internalstaticexternIntPtrGetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling =true, SetLastError =true)]
internalstaticexternboolOpenProcessToken(IntPtrh,intacc,refIntPtrphtok);
[DllImport("advapi32.dll", SetLastError =true)]
internalstaticexternboolLookupPrivilegeValue(strinGhost,stringname,reflongpluid);
[DllImport("advapi32.dll", ExactSpelling =true, SetLastError =true)]
internalstaticexternboolAdjustTokenPrivileges(IntPtrhtok,booldisall,
refTokPriv1Luidnewst,intlen,IntPtrprev,IntPtrrelen);
[DllImport("user32.dll", ExactSpelling =true, SetLastError =true)]
internalstaticexternboolExitWindowsEx(intflg,intrea);
internalconstintSE_PRIVILEGE_ENABLED = 0x00000002;
internalconstintTOKEN_QUERY = 0x00000008;
internalconstintTOKEN_ADJUST_PRIVILEGES = 0x00000020;
internalconststringSE_SHUTDOWN_NAME ="SeShutdownPrivilege";
internalconstintEWX_LOGOFF = 0x00000000;
internalconstintEWX_SHUTDOWN = 0x00000001;
internalconstintEWX_REBOOT = 0x00000002;
internalconstintEWX_FORCE = 0x00000004;
internalconstintEWX_POWEROFF = 0x00000008;
internalconstintEWX_FORCEIFHUNG = 0x00000010;
privatestaticvoidDoExitWin(intflg)
{
boolok;
TokPriv1Luidtp;
IntPtrhproc = GetCurrentProcess();
IntPtrhtok =IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,refhtok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME,reftp.Luid);
ok = AdjustTokenPrivileges(htok,false,reftp, 0,IntPtr.Zero,IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
}
privatevoidbutton2_Click(objectsender,EventArgse)
{
//此代码实现重启功能
DoExitWin(EWX_REBOOT);
}
privatevoidbutton3_Click(objectsender,EventArgse)
{
//此代码实现注销功能
DoExitWin(EWX_LOGOFF);
}
privatevoidbutton1_Click_1(objectsender,EventArgse)
{
//此代码实现关机功能
DoExitWin(EWX_SHUTDOWN);
}
新闻热点
疑难解答