Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Mobile .NET » Monitor Internet Connection State

Monitor Internet Connection State

This article describes an easy approach to building two controls used to monitor the status of an internet connection and provide the user with some indication of that status. Within the attached project, there are two controls, one shows the user what the connection type is and whether or not the machine is connected or offline, the other one is used to show some indication of the quality of the connection in terms of whether or not the connection is good, intermittent, or offline.

Author Rank :
Page Views : 36351
Downloads : 1463
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ConnectStatusCode.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
Become a Sponsor
 Tag Cloud
Image Brush Image Brush in Windows Phone 7 MediaElement in Windows Phone 7 Mobile Internet Toolkit Mobile Internet Toolkit using VB.NET Windows Phone 7 Windows Phone 7 Image Brush Windows Phone 7 MediaElement Windows Phone 7 MediaElement control Advanced Controls Advanced Controls of Mobile Internet Advanced Controls of Mobile Internet in VB.NET Controls of Mobile Internet I-MODE Client Mail sending Application in ASP.NET MediaElement control Mobile Banking Application in ASP.NET Mobile Banking Application in VB.NET Mobile Mail sending Application Mobile Mail sending Application in VB.NET Mobile Programming & the I-MODE Client Mobile Programming & the I-MODE Client in VB.NET User Interface Controls User Interface Controls of Mobile Internet User Interface Controls of Mobile Internet in VB.NET
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction: 

This article describes an easy approach to building two controls used to monitor the status of an internet connection and provide the user with some indication of that status.  Within the attached project, there are two controls, one shows the user what the connection type is and whether or not the machine is connected or offline, the other one is used to show some indication of the quality of the connection in terms of whether or not the connection is good, intermittent, or offline.

The purpose of the controls was to provide a mobile user of a smart client application some status information regarding the internet connection; in this instance, there were many forms within the application and I wanted a simple control to drop on each form to provide that status.

Figure 1:  Both Connection Status Controls In Use

Getting Started:

In order to get started, unzip the attachment and load the solution into Visual Studio 2005.  Examine the solution explorer and note the files contained each of the two projects:

Figure 2:  The Solution Explorer Showing the Project Files

The "ConnectStatus" project contains the two controls used to display internet connection status to the user;  the "ConnectQualityView" displays an indication of the quality of the status based upon how well that connection is maintained over time.  The "ConnectStateView" control shows the type of connection and provides a graphic indicating whether or not the connection is active or offline.

The second project, "TestAppForInetConnect" contains a simple form used to display both controls at the same time.  This second project is not necessary as with Visual Studio 2005, the user may display the controls in the control test container.  There is no code associated with this second project, the main form has one of each type of control loaded into it and it serves only as a container for those controls.

The Code:  ConnectStateView.

The control is quite simple; the visual elements include only a group box and a single label.  Aside from the visual elements, there is a single timer which is used to check the status of the internet connection repeatedly and there is a single image list which is used to hold a couple of images used to place an icon adjacent to the label control.

If you care to open the class, you will note that there are no imports.  The control's code is pretty easy to read and is as follows:

Public Class ConnectStateView

 

#Region "Declarations"

 

    Private ConnectionStateString As String

 

    Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef _

    lpSFlags As Int32, ByVal dwReserved As Int32) As Boolean

 

    Public Enum InetConnState

        modem = &H1

        lan = &H2

        proxy = &H4

        ras = &H10

        offline = &H20

        configured = &H40

    End Enum

 

#End Region 

 

#Region "Control Methods"

 

    Private Sub ConnectStateView_Load(ByVal sender As Object, ByVal e As

    System.EventArgs) Handles Me.Load

 

        Timer1.Enabled = True

 

    End Sub 

 

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As

    System.EventArgs) Handles Timer1.Tick

 

        Dim blnState As Boolean

        blnState = CheckInetConnection()

        lblConnectStatus.Text = "          Connection Type:  " &

        ConnectionStateString

 

    End Sub 

 

    Function CheckInetConnection() As Boolean

 

        Dim lngFlags As Long

 

        If InternetGetConnectedState(lngFlags, 0) Then

            ' True

            If lngFlags And InetConnState.lan Then

                ConnectionStateString = "LAN."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.modem Then

                ConnectionStateString = "Modem."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.configured Then

                ConnectionStateString = "Configured."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.proxy Then

                ConnectionStateString = "Proxy"

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.ras Then

                ConnectionStateString = "RAS."

                lblConnectStatus.Image = ImageList1.Images(1)

            ElseIf lngFlags And InetConnState.offline Then

                ConnectionStateString = "Offline."

                Me.lblConnectStatus.Image = ImageList1.Images(2)

            End If

        Else

            ' False

            ConnectionStateString = "Not Connected."

            lblConnectStatus.Image = ImageList1.Images(3)

        End If

 

    End Function 

 

#End Region 

End Class

In the beginning of the code, note that there is a region called "Declarations" defined and within that region there are three declarations.  The first declaration defines a string value that is used to keep track of the connection type used by the client's machine. 

The next declaration is the most important part of the code, it is the code that exposes a function from the wininet.dll to the application; that function is called "InternetGetConnectedState".  This function accepts two arguments which in this case are two 32 bit integers; these could be longs but integers work fine here; the function returns a boolean but also could be set up to return a long integer as well.  In use, empty values of the specified data types are passed to this function and the function then sets their values.  To use the control, these set values are evaluated in code to determine the type and status of the current internet connection.

The last declaration is of an enumeration used to contain representatives of each connection type exposed by the previous function.  The flags identified in the enumeration are representative of each connection type that may be returned from making a call to the wininet.dll function declared previously.

After the declarations region is closed, a new region entitled "Control Methods" is defined.  The first item in this section is the control load event handler; in this section, the timer is enabled and process of polling the internet connection of the timer's interval is initialized.

After the load event code, the handler for the timer is defined.  The handler is used to evoke the "InternetGetConnectedState" function through a call to the "CheckInetConnect" method.  This code calls the next method in line, "CheckInetConnection" which sets the text contained in the label based upon the value of the "ConnectionStateString" which is in turn updated by the "CheckInetConnection" method.

The "CheckInetConnection" method  calls the wininet.dll method "InternetGetConnectedState" which in turn sets the flag and connection type arguments used to determine the status of the internet connection.  At the beginning of the evaluation, the first check determines whether or not the machine is connected; if the machine is connected, each pair is evaluated to determine the type of connection and to set the label text and icon to reflect the status returned by the method.  If the connection is not active, the else block will execute and the label text and icon will update to show that the system is not connected (see bottom control in figure 3).

Figure 3:  Connection Status Controls with Failed Internet Connection

That is all there is to the code for this first control.  The next section will discuss the content of the second control as used to gauge the quality of an internet connection.

The Code:  ConnectQualityView.

This control is used to give a rough estimate as the quality of the internet connection as a function of the durability and persistence of the connection over a brief time span (3 seconds).  The code contained within this class if nearly identical to the previous class; it is as follows:

Public Class ConnectQualityView 

 

#Region "Declarations"

 

    Dim ConnectionQualityString As String = "Off"

 

    Private Declare Function InternetGetConnectedState Lib "wininet.dll" (ByRef _

    lpSFlags As Int32, ByVal dwReserved As Int32) As Boolean

 

    Public Enum InetConnState

        modem = &H1

        lan = &H2

        proxy = &H4

        ras = &H10

        offline = &H20

        configured = &H40

    End Enum

 

#End Region 

 

#Region "Control Methods" 

 

    Private Sub ConnectQualityView_Load(ByVal sender As Object, ByVal e As

    System.EventArgs) Handles Me.Load

 

        Timer1.Enabled = True

        Me.DoubleBuffered = True

 

    End Sub 

 

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As

    System.EventArgs) Handles Timer1.Tick

 

        lblConnectStatus.Refresh()

 

        Dim blnState As Boolean

        blnState = CheckInetConnection()

 

    End Sub 

 

    Function CheckInetConnection() As Boolean

 

        Dim lngFlags As Long

 

        If InternetGetConnectedState(lngFlags, 0) Then

            ' True

            If lngFlags And InetConnState.lan Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

                Me.Refresh()

            ElseIf lngFlags And InetConnState.modem Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.configured Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.proxy Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.ras Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            ElseIf lngFlags And InetConnState.offline Then

                Select Case ConnectionQualityString

                    Case "Good"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Intermittent"

                        lblConnectStatus.ForeColor = Color.Green

                        lblConnectStatus.Text = "Connection Quality:  Good"

                        ConnectionQualityString = "Good"

                    Case "Off"

                        lblConnectStatus.ForeColor = Color.DarkOrange

                        lblConnectStatus.Text = "Connection Quality:  Intermittent"

                        ConnectionQualityString = "Intermittent"

                End Select

            End If

        Else

            ' False

            Select Case ConnectionQualityString

                Case "Good"

                    lblConnectStatus.ForeColor = Color.DarkOrange

                    lblConnectStatus.Text = "Connection Quality:  Intermittent"

                    ConnectionQualityString = "Intermittent"

                Case "Intermittent"

                    lblConnectStatus.ForeColor = Color.Red

                    lblConnectStatus.Text = "Connection Quality:  Off"

                    ConnectionQualityString = "Off"

                Case "Off"

                    lblConnectStatus.ForeColor = Color.Red

                    lblConnectStatus.Text = "Connection Quality:  Off"

                    ConnectionQualityString = "Off"

            End Select

        End If

 

    End Function 

 

#End Region 

End Class

In reviewing this code in contrast to the previous class described, you will see the only real difference is that the status is used to set the text and fore color of the label control used to display the status, and you will notice that the previous status message (gathered 1.5 seconds earlier) is evaluated to determine how to the display the status of the connection.  This operates under a simple notion of promoting the status of the connection for remaining active over time.  The control initializes with the connection quality string value set to "Off", when the connection state is evaluated, the initial connection state is noted and the code promotes the status to intermittent.  If the status remains active for an additional 1.5 seconds, it is promoted to "Good".    The idea here is that if the connection is dropping off and getting picked back up, the code will continually evaluate the current status against the previous status and promote or demote the status between the three available options of  Good, Intermittent, and Off.

Naturally you may alter the amount of time between status checks and in so doing, increase or decrease the amount of time necessary to promote or demote the status of the connection.

That is all there is to the second control.

Summary.

Whilst this example project demonstrates a couple of ways in which you can monitor and display status regarding a machine's internet connection, these approaches do not represent all of the ways that you may accomplish this task.  Still and all, this approach is a simple and easy way to display connection status information to your users.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Mindcracker MVP Summit 2012
Become a Sponsor
 Comments
Hi... by Aamir On November 6, 2007
Cool article.... Anyway to block internet access?
Reply | Email | Modify 
Re: Hi... by Scott On November 6, 2007
Sure.  The easiest way would be use a firewall; something like Comodo or Internet Access Controller 2007.  If you just wanted to block access when your program was running, you could block the browsers from launching.
Reply | Email | Modify 
comment by thabiso On December 27, 2010
thanks for the share this has helped me a lot,but is there any code that will help by blocking and unblocking internet access
Reply | Email | Modify 
comment and a question by thabiso On December 27, 2010
thanks for the share this has helped me a lot,but is there any code that will help by blocking and unblocking internet access
Reply | Email | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.