实时检测网络状态及是否可以连接Internet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
namespace NetWork
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
NetworkChange.NetworkAddressChanged+=new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
}
public void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface n in adapters)
{
if(n.NetworkInterfaceType!= NetworkInterfaceType.Loopback)
Console.WriteLine("Changed {0} is {1}", n.Name, n.OperationalStatus);
}
Console.WriteLine("NetState : " + NetState());
}
public void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
Console.WriteLine("IsAvailable : "+e.IsAvailable);
Console.WriteLine("NetState : " + NetState());
}
[DllImport("wininet.dll")]
public static extern bool InternetGetConnectedState(out long lpdwFlags, long dwReserved);
public static bool NetState()
{
//string url = http://www.baidu.com/;
//if (url.StartsWith("http://")) url = url.Remove(0, "http://".length/);
//try
//{
// System.Net.IPHostEntry ipHost = System.Net.Dns.GetHostEntry(url);// System.Net.Dns.Resolve(url);
// return true;
//}
//catch //(System.Net.Sockets.SocketException se)
//{
// //System.Diagnostics.Trace.Write(se.Message);
// return false;
//}
try
{
long lfag;
if (InternetGetConnectedState(out lfag, 0))
{
return true;
}
return false;
}
catch
{
return false;
}
}
}
}