您的位置:首页 > 编程语言 > C#

C#电脑重启,关机,注销

2012-10-13 10:46 337 查看
/// <summary>

/// 电脑管理工具类

/// </summary>

public class ComputerManageLib

{

#region API

/// <summary>

/// 设置系统时间

/// </summary>

/// <param name="time"></param>

/// <returns></returns>

[DllImport("kernel32.dll")]

private static extern bool SetLocalTime(ref SYSTEMTIME time);

/// <summary>

/// 获取当前进程的一个伪句柄

///  只要当前进程需要一个进程句柄,就可以使用这个伪句柄。

///  该句柄可以复制,但不可继承。

///  不必调用CloseHandle函数来关闭这个句柄

/// </summary>

/// <returns></returns>

[DllImport("kernel32.dll", ExactSpelling = true)]

internal static extern IntPtr GetCurrentProcess();

[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]

internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);

[DllImport("advapi32.dll", SetLastError = true)]

internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);

[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]

internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,

ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]

internal static extern bool ExitWindowsEx(int flg, int rea);

#endregion

#region 属性

#region 字段

static string _StringS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabckefghijklmnopqrstuvwxyz";

static string _StringN = "0123456789";

/// <summary>

/// 随机种子

/// </summary>

public static Random StaticRandom = new Random();

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;

#endregion

/// <summary>

/// 系统时间参数

/// </summary>

[StructLayout(LayoutKind.Sequential)]

private struct SYSTEMTIME

{

public short year;

public short month;

public short dayOfWeek;

public short day;

public short hour;

public short minute;

public short second;

public short milliseconds;

}

[StructLayout(LayoutKind.Sequential, Pack = 1)]

internal struct TokPriv1Luid

{

public int Count;

public long Luid;

public int Attr;

}

#endregion

#region 方法

/// <summary>

/// 得到指定长度的字符串

/// </summary>

/// <param name="Length">指定长度</param>

/// <returns></returns>

public static string GetLengthStr(int Length)

{

StringBuilder Sb = new StringBuilder();

if (Length < 6)

Length = 6;

for (int i = 0; i < 4; i++)

{

Sb.Append(_StringS[StaticRandom.Next(_StringS.Length)]);

}

int max = Length - 4;

for (int i = 0; i < max; i++)

{

Sb.Append(_StringN[StaticRandom.Next(_StringN.Length)]);

}

return Sb.ToString();

}

/// <summary>

/// 设置系统时间

/// </summary>

/// <param name="dateTime">要设置的时间</param>

public static bool SetSysTime(DateTime dateTime)

{

try

{

SYSTEMTIME st;

st.year = (short)dateTime.Year;

st.month = (short)dateTime.Month;

st.dayOfWeek = (short)dateTime.DayOfWeek;

st.day = (short)dateTime.Day;

st.hour = (short)dateTime.Hour;

st.minute = (short)dateTime.Minute;

st.second = (short)dateTime.Second;

st.milliseconds = (short)dateTime.Millisecond;

return SetLocalTime(ref st);

}

catch (Exception ex)

{

System.Diagnostics.Debug.Print(ex.ToString());

return false;

}

}

/// <summary>

/// 重启电脑

/// </summary>

public static void RestartComputer()

{

Process CmdP1 = new Process();

CmdP1.StartInfo.FileName = "cmd.exe";

CmdP1.StartInfo.UseShellExecute = false;

CmdP1.StartInfo.RedirectStandardInput = true;

CmdP1.StartInfo.RedirectStandardOutput = true;

CmdP1.StartInfo.CreateNoWindow = true;

CmdP1.Start();

CmdP1.StandardInput.WriteLine("shutdown -r -f -t 0");

CmdP1.StandardInput.WriteLine("exit");

CmdP1.Close();

}

/// <summary>

/// 关闭电脑

/// </summary>

public static void PowerOffComputer()

{

Process CmdP1 = new Process();

CmdP1.StartInfo.FileName = "cmd.exe";

CmdP1.StartInfo.UseShellExecute = false;

CmdP1.StartInfo.RedirectStandardInput = true;

CmdP1.StartInfo.RedirectStandardOutput = true;

CmdP1.StartInfo.CreateNoWindow = true;

CmdP1.Start();

CmdP1.StandardInput.WriteLine("shutdown -s -t 3");

CmdP1.StandardInput.WriteLine("exit");

CmdP1.Close();

}

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

}

/// <summary>

/// 重启

/// </summary>

public static void Reboot()

{

DoExitWin(EWX_FORCE | EWX_REBOOT);

}

/// <summary>

/// 关机

/// </summary>

public static void PowerOff()

{

DoExitWin(EWX_FORCE | EWX_POWEROFF);

}

/// <summary>

/// 注销

/// </summary>

public static void LogoOff()

{

DoExitWin(EWX_FORCE | EWX_LOGOFF);

}

#endregion

///// <summary>

///// 获取 网关地址

///// </summary>

///// <returns></returns>

//public static string GetGateWay()

//{

// ManagementClass mMC = new ManagementClass("Win32_NetworkAdapterConfiguration");

// if (mMC == null) return string.Empty;

// ManagementObjectCollection mNICs = mMC.GetInstances();

// if (mNICs == null) return string.Empty;

// string mGetGateWay = string.Empty;

// foreach (ManagementObject nic in mNICs)

// {

// try

// {

// if (Convert.ToBoolean(nic["ipEnabled"]) == true)

// {

// if (nic != null && nic["DefaultIPGateway"] != null)

// mGetGateWay = (nic["DefaultIPGateway"] as String[])[0];

// }

// }

// finally { }

// }

// return mGetGateWay;

//}

///// <summary>

///// 获取本机网卡IP地址

///// </summary>

///// <returns></returns>

//public static string GetLocalIP()

//{

// string hostname;

// System.Net.IPHostEntry localhost;

// System.Net.IPAddress localaddr;

// hostname = System.Net.Dns.GetHostName();

// localhost = System.Net.Dns.GetHostEntry(hostname);

// localaddr = localhost.AddressList[0];

// return localaddr.ToString();

//}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: