2008年11月21日 ..:: Forum ::.. 注册  登录
 导航

 打印   
 搜索


 打印   
 友情链接

 打印   
 论坛
搜索论坛首页
  聚合  IT  Dot Net  how to detect i...
 how to detect internet connection in .Net
 
AD Robot
 2007/8/24 0:00:00
用户离线FengLiN
124个帖子
www.huachaojune.com
第四




how to detect internet connection in .Net

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


看贴是缘分, 顶贴是友情.
  聚合  IT  Dot Net  how to detect i...

搜索搜索  论坛首页论坛首页    打印   
Copyright 2008 by 三片叶   服务条款  隐私声明