经过在网上及MSDN中查询,知道一些关于win2000关机的代码。改写成C#代码后如下:
using System;
using System.Runtime.InteropServices;
using System.IO;
namespace AutoExitWindows
{
/// <summary>
/// ExitWindows 的摘要说明。
/// 关机、注销windows.
/// </summary>
///
public class ExitWindows
{
public const int EWX_LOGOFF = 0; //退出(注销)
public const int EWX_SHUTDOWN = 1; //'关机
public const int EWX_REBOOT = 2; //'重启动
public const int EWX_FORCE = 4;// '强制关机,即不通知现在活动应用程序让其先自我关闭
public const int TOKEN_ADJUST_PRIVILEGES = 0x20;
public const int TOKEN_QUERY = 0x8;
public const int SE_PRIVILEGE_ENABLED = 0x2;
public const int ANYSIZE_ARRAY = 1;
struct LUID
{
int lowpart;
int highpart;
LUID(int low, int high)
{
lowpart=low;
highpart=high;
}
}
struct LUID_AND_ATTRIBUTES
{
LUID pLuid;
int Attributes;
public LUID_AND_ATTRIBUTES(LUID luid, int attributes)
{
pLuid=luid;
Attributes=attributes;
}
}
struct TOKEN_PRIVILEGES
{
int PrivilegeCount;
LUID_AND_ATTRIBUTES Privileges;
public TOKEN_PRIVILEGES(int privilegecount, LUID_AND_ATTRIBUTES privileges)
{
PrivilegeCount=privilegecount;
Privileges=privileges;
}
}
[DllImport("user32",SetLastError=true)]
static extern int ExitWindowsEx(int uFlags, int dwReserved);
[DllImport("kernel32",SetLastError=true)]
static extern int GetCurrentProcess();
[DllImport("advapi32",SetLastError=true)]
static extern int LookupPrivilegeValue(string lpSystemName, string lpName,ref LUID lpLuid);
[DllImport("advapi32",SetLastError=true)]
static extern int AdjustTokenPrivileges(int TokenHandle, int DisableAllPrivileges,TOKEN_PRIVILEGES NewState, int BufferLength, ref TOKEN_PRIVILEGES PreviousState,int ReturnLength);
[DllImport("advapi32",SetLastError=true)]
static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int TokenHandle);
public ExitWindows()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public void CloseWindows(int exittype)
{
AdjustTokenPrivilegesForNT();
ExitWindowsEx( exittype, 0);
}
//这个函数就是用于NT关机中使用的
public static void AdjustTokenPrivilegesForNT()
{
int hdlProcessHandle=0;
int hdlTokenHandle=0;
LUID tmpLuid=new LUID();
TOKEN_PRIVILEGES tkp;
TOKEN_PRIVILEGES tkpNewButIgnored=new TOKEN_PRIVILEGES();
int lBufferNeeded=0;
hdlProcessHandle = GetCurrentProcess();
OpenProcessToken( hdlProcessHandle, TOKEN_ADJUST_PRIVILEGES, ref hdlTokenHandle);
LookupPrivilegeValue( "", "SeShutdownPrivilege", ref tmpLuid);
LUID_AND_ATTRIBUTES luidtemp=new LUID_AND_ATTRIBUTES(tmpLuid, SE_PRIVILEGE_ENABLED);
tkp=new TOKEN_PRIVILEGES(1,luidtemp);
AdjustTokenPrivileges( hdlTokenHandle, 0, tkp, 100, ref tkpNewButIgnored, lBufferNeeded);
}
}
}
调用时
ExitWindows exittemp=new ExitWindows();
exittemp.CloseWindows(4);
经调试,这样只能注销用户,而不能关机。
目前还没有找到能真正关机的代码,有待寻找和改进。