記得大一的時候,一個校園網的幾多同學朋友用i,每當自己開著在下載視頻教程,然後就去左上課,點知道返來就發現,網又比人地用左,白白浪費滴電
後來就想到用C#做一個判斷當前機子是否連網,假如無個話設定關機,米就可以慳翻滴電,環保撒。呵呵
namespace MIS
{
public partial class Close2 : Form
{
System.Net.NetworkInformation.Ping ping;
System.Net.NetworkInformation.PingReply res;
public Close2()
{
InitializeComponent();
}
private void Close2_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
ping = new System.Net.NetworkInformation.Ping();
try
{
res = ping.Send("http://www.google.cn/"); //
if (res.Status != System.Net.NetworkInformation.IPStatus.Success)
{
//沒有聯上Internet哦,做下自己想做個事情咯
timer1.Stop();
MIS.Close.DoExitWin(); //關機咯
}
}
catch(Exception er)
{
//裡你,仲系當你斷網咯,做下自己想做個事情咯
timer1.Stop();
MIS.Close.DoExitWin(); //關機咯
}
}
}
}
//關機程式
using System.Runtime.InteropServices; //
using Microsoft.Win32; //
namespace MIS
{
public class Close
{
/// <summary>
///關閉電腦
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
[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);
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;
public static void DoExitWin()
{
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(EWX_SHUTDOWN, 0);
}
}
}