用c#监控网络状态

时间:2020-12-28 23:45:58

1.查询当前网络状态:

using  Microsoft.VisualBasic.Devices;

//判断当前网络连接状态

Network nw=new Network();

if(nw.IsAvailable)

    lbmsg.Text="网络已连接";

else

    lbmsg.Text="网络已断开";

2.实时监控网络状态

using System.Net.NetworkInformation;
// Constructor
public MainPage()
{
InitializeComponent(); // Subscribe to the NetworkAvailabilityChanged event
DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(NetworkAvailabilityChanged);
} void NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
{ string msg="";
if(e.IsAvailable)
{
msg="网络已连接"; }
else
{
msg="网络已断开";
}
Dispatcher.BeginInvoke(() => {
lbmsg.Text =msg; });
}