首先要導入對命名空間
usingSystem.Runtime.InteropServices;
的引用
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internalstructTok 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); }
新聞熱點
疑難解答