Click here to Skip to main content
15,885,782 members
Articles / Desktop Programming / Windows Forms
Article

Display an Internet Connection status icon using .NET Framework 2.0

Rate me:
Please Sign up or sign in to vote.
4.74/5 (14 votes)
20 Jul 20052 min read 70.5K   2K   66   7
This article explains how to use a BackgroundWorker and a StatusStrip to display an Internet connection status icon on a StatusStrip using .NET Framework 2.0.

Sample Image - InternetConnectionStatusScreenShot.jpg

Introduction

More and more likely, applications depend on an available Internet connection to perform business-layered operations such as invoking web services, obtaining data, and so on. Usually you would like to know if the current environment is really connected. There are multiple approaches to accomplish this, you could check the state of every NetworkInterface using the System.Net namespace, but then having an Ethernet connection or similar doesn’t really tell you if there is an available Internet connection or not.

This article shows a way to get a simple icon on a StatusStrip that shows if the computer is or is not connected to the Internet.

Using the code

Basically you want to get a Timer to perform an HTTP-GET in order to see if a specific website is or is not available.

The only requirement for this kind of functionality is that we don’t want to stop the current UI thread. Therefore, I am using a BackgroundWorker object to perform the query. The BackgroundWorker object declares the DoWork method which defines a custom event handler that defines the DoWorkEventArgs class in which you pass the actual result back into the UI thread. It is very important that you don’t try to interact with any UI element at this method since this is running on a separate thread.

C#
private void InitializeComponent()
{
    // Background Worker
    this._worker = new BackgroundWorker();
    this._worker.WorkerReportsProgress = false;
    this._worker.WorkerSupportsCancellation = false;
    this._worker.DoWork += new 
       DoWorkEventHandler(this.BackgroundWorker_DoWork);
    this._worker.RunWorkerCompleted += new 
       RunWorkerCompletedEventHandler(this.BackgroundWorker_RunWorkerCompleted);

    // Timer
    this._updateTimer = new Timer();
    this._updateTimer.Enabled = !this.DesignMode;
    // Enabled when not in design mode

    this._updateTimer.Tick += delegate { this.OnTick(); };
}

private void OnTick()
{
    if (this.DesignMode)
        return;

    // Stop the timer while the process is running
    this._updateTimer.Enabled = false;

    // Disable so we get the grayed-out look
    this.Enabled = false;
    this.Invalidate();

    // Execute the Ping Query on a separate thread...
    this._worker.RunWorkerAsync();
}

The query is really simple, I execute a simple HttpWebRequest against an URL that should be “always” available, for example your corporate website, http://www.microsoft.com, or http://www.google.com. At the end of the day this is the only way to actually know if you do or do not have an available internet connection.

C#
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        // Create an HTTP Web request
        // to an Uri that's always available.
        HttpWebRequest request = (HttpWebRequest) 
           HttpWebRequest.Create(this._alwaysAvailableUrl);

        // Perform GET
        HttpWebResponse response = 
           (HttpWebResponse) request.GetResponse();
        if (HttpStatusCode.OK == response.StatusCode)
        {
            // HTTP = 200, close the request and return true
            response.Close();
            e.Result = true;
        }
        else
        {
            // Other status; return false
            e.Result = false;
        }
    }
    catch (WebException)
    {
        // Deffinitely offline
        e.Result = false;
    }
}

After the BackgroundWorker object has completed its work (defined in the DoWork event), it calls the RunWorkerCompleted event, which also defines a custom event handler that declares the RunWorkerCompletedEventArgs class. With this class, we will manage the way in which the ToolStripStatusLabel will render.

C#
private void BackgroundWorker_RunWorkerCompleted(object 
                   sender, RunWorkerCompletedEventArgs e)
{
    if (null != e.Error)
    {
        // Throw the error to the User Interface...
        // This shouldn't really get to happen.
        Trace.TraceError(e.Error.Message);
        throw e.Error;
    }
    else
    {
        if ((bool) e.Result) // Online
        {
            this.Image = Properties.Resources.Online;
            this.Text = Properties.Resources.MainFormConnectionStatusOnline;
        }
        else // Offline
        {
            this.Image = Properties.Resources.Offline;
            this.Text = Properties.Resources.MainFormConnectionStatusOffline;
        }

        // Redraw
        this.Invalidate();
    }

    // Re-enable and restart timer...
    this.Enabled = true;
    this._updateTimer.Enabled = true;
}

Conclusion

.NET Framework 2.0 makes really easy using background threads, giving your UI a smooth and useful experience. Now, if you are using the April CTP of Visual Studio .NET 2005, I strongly recommend that you manually assign your delegate for the DoWork event, since there is a bug in VS.NET that when it tries to re-write the comment of not using UI code from the separate thread it can replace your actual code.

If you need an Internet connection for using a Web Service you may also want to consider using adding a GetVersion Web Method into your Web Service and trying to access this service since after all there is no point of having an available connection if your web server is down.

History

  • Demo version - 1.0.0.0 - attached to this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalfor post to show internet connection is ctive or not.......................... Pin
mrpatel.ce2-Jan-14 0:30
mrpatel.ce2-Jan-14 0:30 
GeneralNice code Pin
Martin Marconcini25-Apr-08 8:33
Martin Marconcini25-Apr-08 8:33 
Generalgetting error. ... Pin
patibandha sapan23-Sep-07 23:25
patibandha sapan23-Sep-07 23:25 
GeneralCool work Pin
HankiDesign6-Jul-07 8:29
HankiDesign6-Jul-07 8:29 
GeneralConvert it Visual Studio 8 Pin
DeadBob23-Jan-06 13:57
DeadBob23-Jan-06 13:57 
Generalon exception... Pin
Antonio Dias20-Sep-05 12:50
Antonio Dias20-Sep-05 12:50 
GeneralNice :) Pin
WebMaster21-Jul-05 7:37
WebMaster21-Jul-05 7:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.