1. [DllImport("wininet.dll")] private extern static bool InternetGetConnectedState(out int Description, int ReservedValue); public static bool IsConnectedToInternet() { int Desc; return InternetGetConnectedState(out Desc, 0); }
2. Auto Detect:
using System; using System.Threading; using System.Windows.Forms; using Timer = System.Threading.Timer; namespace Born2Code.Net { public enum ConnectionState { Unknown, Connected, Disconnected }; public class ConnectionMonitor { public EventHandler Connected; public EventHandler Disconnected; private ConnectionState _state; private System.Threading.Timer _timer; private Int32 _waitTime = 2500; // 2.5 seconds. public int WaitTime { get { return _waitTime; } set { if( !_waitTime.Equals( value ) ) { _timer.Change( value, Timeout.Infinite ); } } } public ConnectionMonitor() { _state = ConnectionState.Unknown; _timer = new Timer( new TimerCallback( TimerTick ), null, WaitTime, Timeout.Infinite ); } private void TimerTick( Object notused ) { bool connected = IsNetworkConnected(); if( connected ) { if( _state != ConnectionState.Connected ) { _state = ConnectionState.Connected; OnConnected(); } } else { if( _state != ConnectionState.Disconnected ) { _state = ConnectionState.Disconnected; OnDisconnected(); } } } protected bool IsNetworkConnected() { bool connected = SystemInformation.Network; if (connected) { connected = false; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT NetConnectionStatus FROM Win32_NetworkAdapter"); foreach (System.Management.ManagementObject networkAdapter in searcher.Get()) { if (networkAdapter["NetConnectionStatus"] != null) { if (Convert.ToInt32(networkAdapter["NetConnectionStatus"]).Equals(2)) { connected = true; break; } } } searcher.Dispose(); } return connected; } protected virtual void OnConnected() { if( Connected != null ) { Control target = Connected.Target as Control; if( target != null && target.InvokeRequired ) { Object[] args = new Object[] { this, EventArgs.Empty }; target.Invoke( Connected, args ); } else { Connected( this, EventArgs.Empty ); } } } protected virtual void OnDisconnected() { if( Connected != null ) { Control target = Connected.Target as Control; if( target != null && target.InvokeRequired ) { Object[] args = new Object[] { this, EventArgs.Empty }; target.Invoke( Connected, args ); } else { Connected( this, EventArgs.Empty ); } } } } }