首页 > 学院 > 开发设计 > 正文

C#实现注销、重启和关机代码

2019-11-17 03:01:34
字体:
来源:转载
供稿:网友
C#实现注销、重启和关机代码

首先要导入对命名空间

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);

}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表