Click here to Skip to main content
15,867,330 members
Articles / Desktop Programming / Windows Forms

Toggle Network Connections

Rate me:
Please Sign up or sign in to vote.
3.52/5 (14 votes)
31 Oct 2007CPOL4 min read 87.1K   806   41   26
A class that can enable/disable a Local Area or wireless connection.

Introduction

Have you ever wished you code enable or disable a network connection through code? If so, here you go!

Background

A few weeks ago, someone posted a question on the newsgroups about toggling their network connection on and off. I figured the solution relied someplace in the Windows APIs, so I pulled up MSDN and did a little research, but never found a solution. Fortunately, another poster (who researches better than I) posted a link to some VBScript that would do what the poster asked. I had wanted to convert the file to VB.NET, but since I didn't have a reason for the class, I never got around to it.

But you see, yesterday, I published my first article here on CodeProject, and immediately started searching for something else I could publish an article on. This (as you've probably guessed) brought that old post back to mind. I ran through the Google archives until I found the thread, and opened up the link and got to work.

Giving Credit Where Credit is Due

As mentioned previously, this project is mainly a conversion of a VBScript file. This file was published in an article for MCP Mag by Chris Brooke, titled "Controlling Network Connections". The link can be found here: http://mcpmag.com/columns/article.asp?EditorialsID=619.

The Basics

By no means do I understand the internal tracking system Windows uses for stuff like this. The referenced article above probably does a better job of explaining the technical aspects, but I'll explain it in my own words.

From what I gather, there is a folder that manages both the Local Area and wireless connections. Both of these folders are located in the Network Connections folder, which is in turn located in the Control Panel folder. So what this class does is navigate to the specific folder, grabs the enable or disable verb (something like a command I guess), and then calls its DoIt() method which tells the verb to either enable or disable the connection.

And Now Some Code

Prerequisites

For this code to work, you need to add a reference to the Shell32 DLL. This is normally located at C:\Windows\System32\shell32.dll.

The Properties

The original VBScript file used variables to store the reference and then assigned and validated the values in some in-line code. I decided this was better left to readonly properties; after all, why not encapsulate what you can?

First up is the Control Panel folder. This is probably the simplest one to get; you simple instantiate a shell32.Shell object and use its Namespace method to get the Control Panel folder.

VB
Private Shared ReadOnly Property ControlPanelFolder() As Shell32.Folder
    Get
        Dim shell As New Shell32.Shell()
        Return shell.NameSpace(3)
    End Get
End Property

Next up is the Network Connections folder. This one is found by looping through the items in the Control Panel folder until you find the correct folder (by checking the Name property).

Note that I throw a custom exception if no folder is found. I'll only include the code for this and the other custom exceptions in the complete code, they are more for the name than anything. Also, I don't have any code that actually catches these exceptions; since everyone has their own error handling strategies, I figured I'd leave this part to you.

VB
Private Shared ReadOnly Property NetworkFolder() As Shell32.Folder
    Get

        Dim retVal As Shell32.Folder = Nothing

        For Each fi As Shell32.FolderItem In ControlPanelFolder.Items
            If fi.Name = "Network Connections" Then
                retVal = fi.GetFolder()
            End If
        Next

        If retVal Is Nothing Then
            Throw New NetworkConnectionsFolderNotFoundException()
        Else
            Return retVal
        End If

    End Get
End Property

Finally are the properties for the Local Area and wireless connections. Again, these just loop through the Network Connections folder and get the appropriate folder item based on name.

VB
Private Shared ReadOnly Property LocalAreaConnectionFolderItem() As Shell32.FolderItem
    Get

        Dim retVal As Shell32.FolderItem = Nothing

        For Each folderItem As Shell32.FolderItem In NetworkFolder.Items
            Console.WriteLine(folderItem.Name)
            If InStr(folderItem.Name.ToLower(), _
                     "Local Area Connection".ToLower()) Then
                retVal = folderItem
                Exit For
            End If
        Next

        If retVal Is Nothing Then
            Throw New LocalAreaConnectionFolderItemNotFoundException()
        Else
            Return retVal
        End If

    End Get
End Property

Private Shared ReadOnly Property WirelessConnectionFolderItem() As Shell32.FolderItem
    Get

        Dim retVal As Shell32.FolderItem = Nothing

        For Each folderItem As Shell32.FolderItem In NetworkFolder.Items
            Console.WriteLine(folderItem.Name)
            If InStr(folderItem.Name.ToLower(), _
                     "Wireless Network Connection".ToLower()) Then
                retVal = folderItem
                Exit For
            End If
        Next

        If retVal Is Nothing Then
            Throw New WirelessConnectionFolderItemNotFoundException()
        Else
            Return retVal
        End If

    End Get
End Property

The Methods

This part is pretty simple. The method starts a loop that runs though the available verbs (commands?) in the appropriate folder item (Local Area or wireless) and then executes the verb. I use OrElse in the If Then test because the Enable and Disable verbs are mutually exclusive, as the connection can't be both enabled and disabled (disenabled?). Finally, I throw in a Thread.Sleep(1000) just to make sure the verb have time to activate. I tested the code; without this call, the call to enable the connection was ignored about 50% of the time. This was using a console app though, so it's possible that the verb reference was getting destroyed before it even had time to do anything. Please experiment with this and let me know what you find - as I hate to "pause" an app when it's not needed.

VB
Public Shared Sub ToggleWirelessConnection()
    For Each verb As Shell32.FolderItemVerb In WirelessConnectionFolderItem.Verbs
        If verb.Name = "En&able" OrElse verb.Name = "Disa&ble" Then
            verb.DoIt()
            Exit For
        End If
    Next
    Threading.Thread.Sleep(1000)
End Sub

Public Shared Sub ToggleLocalAreaConnection()
    For Each verb As Shell32.FolderItemVerb In LocalAreaConnectionFolderItem.Verbs
        If verb.Name = "En&able" OrElse verb.Name = "Disa&ble" Then
            verb.DoIt()
            Exit For
        End If
    Next
    Threading.Thread.Sleep(1000)
End Sub

Using the Code

I marked all the methods as Shared so using this code is incredibly simple. Assuming you have added the reference to the Shell32 DLL, all you need to do is:

VB
ToggleNetworkConnection.ToggleLocalAreaConnection()
ToggleNetworkConnection.ToggleWirelessConnection()

The Entire Code

Since I know a lot of people don't want to download a code file for a quick look-see, I figured I'd include this:

VB
Public Class ToggleNetworkConnection

#Region "Public Methods"
     Public Shared Sub ToggleWirelessConnection()
        For Each verb As Shell32.FolderItemVerb In WirelessConnectionFolderItem.Verbs
            If verb.Name = "En&able" OrElse verb.Name = "Disa&ble" Then
                verb.DoIt()
                Exit For
            End If
        Next
        Threading.Thread.Sleep(1000)
    End Sub

    Public Shared Sub ToggleLocalAreaConnection()
        For Each verb As Shell32.FolderItemVerb In LocalAreaConnectionFolderItem.Verbs
            If verb.Name = "En&able" OrElse verb.Name = "Disa&ble" Then
                verb.DoIt()
                Exit For
            End If
        Next
        Threading.Thread.Sleep(1000)
    End Sub

#End Region

#Region "Properties"
     Private Shared ReadOnly Property ControlPanelFolder() As Shell32.Folder
        Get
            Dim shell As New Shell32.Shell()
            Return shell.NameSpace(3)
        End Get
    End Property

    Private Shared ReadOnly Property NetworkFolder() As Shell32.Folder
        Get

            Dim retVal As Shell32.Folder = Nothing

            For Each fi As Shell32.FolderItem In ControlPanelFolder.Items
                If fi.Name = "Network Connections" Then
                    retVal = fi.GetFolder()
                End If
            Next

            If retVal Is Nothing Then
                Throw New NetworkConnectionsFolderNotFoundException()
            Else
                Return retVal
            End If

        End Get
    End Property

    Private Shared ReadOnly Property LocalAreaConnectionFolderItem() As Shell32.FolderItem
        Get

            Dim retVal As Shell32.FolderItem = Nothing

            For Each folderItem As Shell32.FolderItem In NetworkFolder.Items
                Console.WriteLine(folderItem.Name)
                If InStr(folderItem.Name.ToLower(), "Local Area Connection".ToLower()) Then
                    retVal = folderItem
                    Exit For
                End If
            Next

            If retVal Is Nothing Then
                Throw New LocalAreaConnectionFolderItemNotFoundException()
            Else
                Return retVal
            End If

        End Get
    End Property

    Private Shared ReadOnly Property WirelessConnectionFolderItem() As Shell32.FolderItem
        Get

            Dim retVal As Shell32.FolderItem = Nothing

            For Each folderItem As Shell32.FolderItem In NetworkFolder.Items
                Console.WriteLine(folderItem.Name)
                If InStr(folderItem.Name.ToLower(), _
                         "Wireless Network Connection".ToLower()) Then
                    retVal = folderItem
                    Exit For
                End If
            Next

            If retVal Is Nothing Then
                Throw New WirelessConnectionFolderItemNotFoundException()
            Else
                Return retVal
            End If

        End Get
    End Property

#End Region

#Region "Custom Exceptions"
     Public Class NetworkConnectionsFolderNotFoundException
        Inherits Exception

        Public Overrides ReadOnly Property Message() As String
            Get
                Return "The Network Connections Folder Could Not Be Found!"
            End Get
        End Property
    End Class

    Public Class LocalAreaConnectionFolderItemNotFoundException
        Inherits Exception

        Public Overrides ReadOnly Property Message() As String
            Get
                Return "The Local Area Connection Folder Could Not Be Found!"
            End Get
        End Property
    End Class

    Public Class WirelessConnectionFolderItemNotFoundException
        Inherits Exception

        Public Overrides ReadOnly Property Message() As String
            Get
                Return "The Wireless Connection Folder Could Not Be Found!"
            End Get
        End Property
    End Class

#End Region

End Class

History

  • 1/20/2007 - First release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
While young, at only 22 years of age, I constantly am trying to improve my programming skill set. I currently work for an IT technology leader as an ASP.NET/.NET developer in Columbus, Ohio. I was also awarded Microsoft MVP status for Visual Basic for the first time in 2008. It is a great honor to join the team of MVP's worldwide.

Apart from programming, I spend all my time with my lovely and supportive wife (who is carrying our first child). Besides from programming, you can also find me running around the virtual world of World of Warcraft.

Comments and Discussions

 
QuestionAny idea on how to make this work with Vista/Windows 7? Pin
Greg194714-Mar-10 2:20
Greg194714-Mar-10 2:20 
GeneralThere is no folder "Network Connections" in Vista / Windows 7 Pin
gigatoad14-Apr-09 5:06
gigatoad14-Apr-09 5:06 
GeneralRe: There is no folder "Network Connections" in Vista / Windows 7 Pin
morphias0@yahoo.com31-Aug-10 8:04
morphias0@yahoo.com31-Aug-10 8:04 
GeneralThis shall not allways work as items in Network Conections can be renamed with F2 !!!!!!!!!!!!!!!!! Pin
sandi_ro16-Jan-09 3:29
sandi_ro16-Jan-09 3:29 
GeneralRe: This shall not allways work as items in Network Conections can be renamed with F2 !!!!!!!!!!!!!!!!! Pin
Seth Rowe16-Jan-09 4:07
Seth Rowe16-Jan-09 4:07 
GeneralRe: This shall not allways work as items in Network Conections can be renamed with F2 !!!!!!!!!!!!!!!!! Pin
sandi_ro16-Jan-09 7:41
sandi_ro16-Jan-09 7:41 
QuestionError when implementing in Windows Service vb.net Pin
Member 19594426-Aug-08 9:00
Member 19594426-Aug-08 9:00 
QuestionError message Pin
Pete_D_S25-Mar-08 4:29
Pete_D_S25-Mar-08 4:29 
Hi, firstly i'd just like to say this is a really useful post.

Now, my problem is that if i run this from a windows form and click buttons to toggle the connections it works fine. However, i'm monitoring for Network connections changing and asking the change event to invoke you module.
When the event is fired it gives the error
A first chance exception of type 'System.BadImageFormatException' occurred in NLA.exe
Invalid access to memory location. (Exception from HRESULT: 0x800703E6)

Any ideas?
GeneralExcellent work.. but need help Pin
shadysaim16-Mar-08 21:32
shadysaim16-Mar-08 21:32 
GeneralOS Language Pin
WichOnWeb12-Nov-07 4:47
WichOnWeb12-Nov-07 4:47 
GeneralRe: OS Language Pin
Seth Rowe12-Nov-07 5:47
Seth Rowe12-Nov-07 5:47 
QuestionNewby question shell32 Pin
wizardict12-Jul-07 9:09
wizardict12-Jul-07 9:09 
AnswerRe: Newby question shell32 Pin
Seth Rowe12-Jul-07 9:16
Seth Rowe12-Jul-07 9:16 
GeneralRe: Newby question shell32 Pin
wizardict12-Jul-07 14:47
wizardict12-Jul-07 14:47 
GeneralRe: Newby question shell32 Pin
Seth Rowe13-Jul-07 1:23
Seth Rowe13-Jul-07 1:23 
QuestionGetting errror when use your code in windows service .net 2.0 Pin
GNayan200425-Apr-07 0:46
GNayan200425-Apr-07 0:46 
AnswerRe: Getting errror when use your code in windows service .net 2.0 Pin
Seth Rowe25-Apr-07 14:16
Seth Rowe25-Apr-07 14:16 
QuestionRe: Getting errror when use your code in windows service .net 2.0 Pin
Pinhead200013-Sep-07 2:43
Pinhead200013-Sep-07 2:43 
AnswerRe: Getting errror when use your code in windows service .net 2.0 Pin
ilya_margoulis27-Jun-09 8:54
ilya_margoulis27-Jun-09 8:54 
Generalsame thing in C# Pin
pete007_ke4-Apr-07 2:45
pete007_ke4-Apr-07 2:45 
GeneralRe: same thing in C# Pin
Seth Rowe5-Apr-07 2:16
Seth Rowe5-Apr-07 2:16 
GeneralgetFolder Exception Pin
notoriousvic14-Feb-07 11:03
notoriousvic14-Feb-07 11:03 
GeneralRe: getFolder Exception Pin
Seth Rowe15-Feb-07 15:46
Seth Rowe15-Feb-07 15:46 
GeneralRe: getFolder Exception Pin
blabla2319-Aug-07 7:45
blabla2319-Aug-07 7:45 
GeneralRe: getFolder Exception Pin
andre_monteiro13-Nov-07 7:38
andre_monteiro13-Nov-07 7:38 

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.