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
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";
lblNetworkStatus.ForeColor = Color.Red;
lblNetworkStatus.Text = "NetworkStatus: Offline";


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

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