C#实现关机、重启。注销的代码
命名空间引用:using System.Runtime.InteropServices;
此代码为转载,本人未经测试。
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
internal static extern IntPtr GetCurrentProcess();
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
internal static extern bool ExitWindowsEx(int flg, int rea);
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
internal const int EWX_LOGOFF = 0x00000000;
internal const int EWX_SHUTDOWN = 0x00000001;
internal const int EWX_REBOOT = 0x00000002;
internal const int EWX_FORCE = 0x00000004;
internal const int EWX_POWEROFF = 0x00000008;
internal const int EWX_FORCEIFHUNG = 0x00000010;
private static void DoExitWin(int flg)
{
bool ok;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref tp.Luid);
ok = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
ok = ExitWindowsEx(flg, 0);
}
private void button2_Click(object sender, EventArgs e)
{
//此代码实现重启功能
DoExitWin(EWX_REBOOT);
}
private void button3_Click(object sender, EventArgs e)
{
//此代码实现注销功能
DoExitWin(EWX_LOGOFF);
}
private void button1_Click_1(object sender, EventArgs e)
{
//此代码实现关机功能
DoExitWin(EWX_SHUTDOWN);
}
111 电脑还是手机?:o 已经测试了,可以实现,谢谢分享:lol awarenessxie 发表于 2016-5-30 12:53
电脑还是手机?
电脑 meng 发表于 2016-5-30 14:16
已经测试了,可以实现,谢谢分享
ok~~~
页:
[1]