Condividi tramite


Update Windows Form UI with Network Available Change Event

.Net frameworks 2.0 has a new namespace System.Net.NetworkInformation, which you could use to gather various network statistics on the machine, it also provide two interesting events NetworkAddressChanged and NetworkAvailabilityChanged. If you are writing winform application and want to update some UI information based on network availability status, then Network availibility changed event is very handy for you. Look at following few lines of handy code as demo to change a text label in windows form.

First Step is to hook up an event handler on NetworkChange.NetworkAvailabilityChanged event

        public myMainForm()
{          

                        /// Do all your applicatio stuff here
updateNetworkStatus(NetworkInterface.GetIsNetworkAvailable());
NetworkChange.NetworkAvailabilityChanged +=
                             new NetworkAvailabilityChangedEventHandler (myNetworkAvailabilityChangeHandler);
}

Implement the event handler

          public void myNetworkAvailabilityChangeHandler(object sender,
NetworkAvailabilityEventArgs args)
{// you can't update UI here because because windows form UI could be only updated on main UI thread
this.Invoke(new WaitCallback(updateNetworkStatus), args.IsAvailable);
}

Implement the method to update the UI information, in this example a label on form will be updated to show the availability of network, but you can do more cool stuff here

        private void updateNetworkStatus(object state)
{
if ((bool)state)
{
lblNetworkStatus.ForeColor = Color.Green;
lblNetworkStatus.Text = "NetworkStatus: Online";
}
else
{
lblNetworkStatus.ForeColor = Color.Red;
lblNetworkStatus.Text = "NetworkStatus: Offline";
}

   }

NetworkAvailability changed is available in post Beta1 bits, check https://lab.msdn.microsoft.com/vs2005/ for latest bits.

This posting is provided "AS IS" with no warranties, and confers no rights

Comments

  • Anonymous
    December 16, 2004
    hey thanks! good post..
  • Anonymous
    December 16, 2004
    Very cool feature! Now I won't have to resort to various Win32 incantations and other wizardry to figure out the network connection status in my smart client apps. Well done!
  • Anonymous
    January 04, 2008
    PingBack from http://blog.rileytech.net/post/2008/01/Cross-thread-goodness.aspx
  • Anonymous
    January 13, 2009
    How do we notify the client if the server ip address changes. Client will be communicating with old ip address and will not know the new Ip address to send a message.
  • Anonymous
    April 29, 2010
    Nice post. ThanksOne quick question:How we can refresh the network connection from winform aplication?