用c#監控網路狀態

小y發表於2017-07-31

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

 

相關文章