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


Comments (7)
  1. SBC says:

    hey thanks! good post..

  2. 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!

  3. sai says:

    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.

  4. Anuj says:

    Nice post. Thanks

    One quick question:

    How we can refresh the network connection from winform aplication?

Comments are closed.

Skip to main content