Sign in to follow this  
Followers 0
cherdeg

HowTo toggle (disable/enable) a NIC using AutoIt?

22 posts in this topic

Hi All,

HowTo toggle (disable/enable) a NIC using AutoIt?

Yes I searched the forum, yes there are posts with partial solutions. But none of those would work on Windows 2000, XP, Server 2003, Vista and Server 2008.

There must be a solution aside using devcon to hardcore disable the NIC device.

Regards,

Chris

Share this post


Link to post
Share on other sites

Read this post http://www.autoitscript.com/forum/index.ph...st&p=525659

In the code that ptrex posted there is a toggleNic() Function which he used to disable then re-enable the NIC

Thank you very much, but that function NicToggle() is exactly one of the two solutions in whole that can be found here. And, as I wrote above, it won't work in Vista or 2008 Server. To asure you that I already did my homework, here the other way to toggle a NIC (which basically does the same):

$ret = LanToggle('Local Area Connection')

Select
 Case $ret = 1
  MsgBox(0, '', 'Done!')
 Case Else
  MsgBox(0, '', '"Local Area Connection" is not available')
EndSelect


Func LanToggle($lanconnection)
 $status = ''
 $status_ = ''
 $objwmiservice = ObjGet('winmgmts:\\localhost\root\CIMV2')
 $colitems = $objWMIService.ExecQuery ('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x10 + 0x20)
 If IsObj($colitems) Then
  For $objitem In $colitems
   If String($objitem.netconnectionid) = $lanconnection Then
    $status = Not (Not ($objitem.netconnectionstatus))
    ExitLoop
   EndIf
  Next
 EndIf
 $shellapp = ObjCreate('shell.application')
 $ocontrolpanel = $shellApp.Namespace (3)
 For $folderitem In $ocontrolpanel.items
  If $folderitem.name = 'Network Connections' Then
   For $folderitem In $folderitem.getfolder.items
    If StringLower($folderitem.name) = StringLower($lanconnection) Then
     For $verb In $folderitem.verbs
      If $verb.name = 'En&able' Or $verb.name = 'Disa&ble' Then
       $verb.doit
       $exitlantoggle = 0
       While $exitlantoggle = 0
        Sleep(1)
        $colitems = $objWMIService.ExecQuery ('SELECT * FROM Win32_NetworkAdapter', 'WQL', 0x10 + 0x20)
        If IsObj($colitems) Then
         For $objitem In $colitems
          If String($objitem.netconnectionid) = $lanconnection Then $status_ = Not (Not ($objitem.netconnectionstatus))
          If $status = Not ($status_) Then
           $exitlantoggle = 1
           ExitLoop
          EndIf
         Next
        EndIf
       WEnd
       Return 1
      EndIf
     Next
    EndIf
   Next
  EndIf
 Next
 Return 0
EndFunc   ;==>LanToggle

I need another, OS independet way to toggle NICs, maybe by WMI or devcon.exe, intelligently interconnected with the Local Area Connections matching the allocated hardware devices.

Thank you very much,

Best Regards,

Chris

Share this post


Link to post
Share on other sites

Hi all,

regarding my problem...I found the Delphi Code below...is anybody able to convertit to AutoIt?

; Windows VISTA (BORLAND DELPHI)
; ==================================

function EnabelNetworkCard(cardName : String) : integer;
    var Retvar : integer;
        oBindObj : IDispatch;
        oNetAdapters,oNetAdapter,
        oIpAddress,oGateWay,
        oWMIService,oSubnetMask : OleVariant;
        i,iValue : longword;
        oEnum : IEnumvariant;
        oCtx : IBindCtx;
        oMk : IMoniker;
        sFileObj : widestring;
    begin
        Retvar := 0;
        sFileObj := 'winmgmts:\\.\root\cimv2';

        // Connect to WMI - Emulate API GetObject()
        OleCheck(CreateBindCtx(0,oCtx));
        OleCheck(MkParseDisplayNameEx(oCtx,PWideChar(sFileObj),i,oMk));
        OleCheck(oMk.BindToObject(oCtx,nil,IUnknown,oBindObj));
        oWMIService := oBindObj;

        oNetAdapters := oWMIService.ExecQuery('Select * from ' +
                                        'Win32_NetworkAdapter ' +
                                        'where Description = ' + '''' +
        CardName + '''');
        oEnum := IUnknown(oNetAdapters._NewEnum) as IEnumVariant;

    while oEnum.Next(1,oNetAdapter,iValue) = 0 do begin
        try
            ShowMessage(oNetAdapter.Description);
            Retvar := oNetAdapter.Enable;
        except
            Retvar := -1;
        end;
    oNetAdapter := Unassigned;
    end;

    oGateWay := Unassigned;
    oSubnetMask := Unassigned;
    oIpAddress := Unassigned;
    oNetAdapters := Unassigned;
    oWMIService := Unassigned;
    Result := Retvar;
end;

; Windows XP (BORLAND DELPHI)
; ==================================
; here you need to add 'Microsoft Shell Controls and Automation' go
; to Project|Import Type Library, uncheck 'Generate Component Wrapper', 
; Mselect 'Microsoft Shell Controls and Automation', and click Create 
; Unit; then, add Shell32_tlb to your unit's uses clause.

function ToggleLAN(const ConnectionName: string): Boolean;
    const
        EnableVerb = 'En&able';
        DisableVerb = 'Disa&ble';
        LANEnable: Boolean = True;
    var
        ShellApp: Shell32_tlb.Shell;
        ControlPanel: Shell32_tlb.Folder;
        FolderItem: Shell32_tlb.FolderItem;
        NetworkFolder: Shell32_tlb.Folder;
        LANConnection: Shell32_tlb.FolderItem;
        EnableVerbItem, DisableVerbItem, Verb : Shell32_tlb.FolderItemVerb;
        I,K: Integer;
begin
    Result := False;
    ShellApp := CoShell.Create;
    ControlPanel := ShellApp.NameSpace(ssfCONTROLS);
    //  test := ConnectionName;
    for I := 0 to ControlPanel.Items.Count - 1 do
    begin
        FolderItem := ControlPanel.Items.Item(I);
        //    ShowMessage(FolderItem.Name);
        if (FolderItem.Name = 'Network Connections') or
            (FolderItem.Name = 'Network and Dial-up Connections') or
            (FolderItem.Name = 'Network and Sharing Center') then
        begin
            NetworkFolder := FolderItem.GetFolder as Folder;
            Break;
        end;
    end;
    if NetworkFolder = nil then
        begin
        Result := False;
        Exit;
    end;
    for I := 0 to NetworkFolder.Items.Count - 1 do
    begin
        FolderItem := NetworkFolder.Items.Item(I);
        //    ShowMessage(FolderItem.Name);
        if FolderItem.Name = ConnectionName then
        begin
            LANConnection := FolderItem;
            Break;
        end;
    end;

    if LANConnection = nil then
    begin
        Result := False;
        Exit;
    end;

    for I := 0 to LANConnection.Verbs.Count - 1 do
        begin
            if LANConnection.Verbs.Item(I).Name = EnableVerb then
            begin
                EnableVerbItem := LANConnection.Verbs.Item(I);
                LANEnable := True;
                Break;
            end
            else if LANConnection.Verbs.Item(I).Name = DisableVerb then
            begin
                DisableVerbItem := LANConnection.Verbs.Item(I);
                LANEnable := False;
                Break;
            end;
        end;
        if LANEnable then
            EnableVerbItem.DoIt
        else
            DisableVerbItem.DoIt;
            Result := True; 

end;

Please...it would be a great step to be able to completely manage network connections using nothing more than AutoIt.

Regards,

Chris

Share this post


Link to post
Share on other sites

Share this post


Link to post
Share on other sites

Looks like the Deplhi code does the same thing (Uses WMI for Network Connection list and Shell object to en/disable). Does this have what you need?

http://www.autoitscript.com/forum/index.ph...st&p=518804

Yeah, you're right - the code does mainly the same. But when enhancing the AutoIt script from my OP to support the new folder names coming with Vista / 2008 Server, it won't find a Lan Connection. Here the new line:

If $folderitem.name = 'Network Connections' Or $folderitem.name = ' Network and Dial-up Connections' Or $folderitem.name = 'Network and Sharing Center' ThenoÝ÷ ØæÊb*'¶«zËb[zk-¡·¦ºé°Ømçè׫©³ùhq«b¢{^%É*ºLjv x×­Âä
çyËb¢{*ºbØ^ªê-5ëp¢¹Ô¡j¸§'§µêêºmçè׫v+)¬v)íæv·¬±¶«Ê®¢Ð¨Úèö§z]=Ø×­Âä
çyËb¢{*ºAºØ!Ê)ÊØb±§]­ë,¶§¢Ø^­ìiÞ¯§v,ßÖv·¬±¶«jwaÑ'µêíæv·¬²­²·©§u¼ªºBÓÝwhÂÍ=Ù,¬µé·ÛOvrí®^ÅꮢÔázaz»h¢X¬j÷«ÉÊ(ªi®ØZL¨º÷«Êkú+¶¥yßÙyø§×¥{+kÊ)ඬz«¶ÊÒÙ÷öܵÊ&¦W­z®×«²Ö§v+[ºÒ7öj',ÉÛ¶ayö¶ØZµ§(¥y×±{
'ßÛkºz'ÛM

Please help, I'm lost...

Regards,

Chris

Share this post


Link to post
Share on other sites

Hi.

this might give you a start:

"netsh interface show interface ?"

"netsh interface set interface ?"

Good luck, Rudi. :)


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

cherdeg to be able to enable and disable network adapter in Vista and Server 2008 you need to use Win32_NetworkAdapter Class.

Enable Method

Disable Method

I don't have windows Vista or Server 2008 so I haven't test it the script.

_ToggleNetworkInterface('local area connection', 0)

;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _ToggleNetworkInterface($strNetwork, $iFlag = 1)
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $strComputer = "localhost"

    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

    If IsObj($colItems) Then
        For $objItem In $colItems           
            If $objItem.NetConnectionID = $strNetwork Then
                If $iFlag = 0 And $objItem.NetEnabled = True Then
                    $objItem.Disable
                ElseIf $iFlag = 1 And $objItem.NetEnabled = False Then
                    $objItem.Enable
                EndIf
                ExitLoop
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
EndFunc   ;==>_ToggleNetworkInterface

Edit: Added _ToggleNetworkInterface() this function only work in Windows Vista or Server 2008.

Edited by Danny35d

AutoIt Scripts:NetPrinter - Network Printer UtilityRobocopyGUI - GUI interface for M$ robocopy command line

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

Hi.

this might give you a start:

"netsh interface show interface ?"

"netsh interface set interface ?"

Good luck, Rudi. :)

Okay Rudi, thank you so far. And how should, in you opinion, the whole command look like, if the Interface/Connection had the name "Local Area Connection"? Your advice quite misplaced, as if you hadn't understood my problem ("HowTo toggle (disable/enable) a NIC using AutoIt?"). The "netsh" utilitiy was, for me as an Admin, the ever 1st point to look at as I started searching for a way to programmatically diasble/enable LAN Connections. For your information - the output of:

"netsh interface set interface name="Local Area Connection" admin=disabled"

or:

"netsh interface set interface name="Local Area Connection" connect=disconnected"

...is:

"One or more essential parameters not specified

The syntax supplied for this command is not valid. Check help for the correct syntax."

While this error message is not quite clear, because you can see that the command is right e.g. here at Microsoft's Technet, reading the output further will let you discover that all these commands can only be used for "demand dial"- or "RAS" connections and NOT for LAN-connections.

Regards,

Chris

Edited by cherdeg

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

cherdeg to be able to enable and disable network adapter in Vista and Server 2008 you need to use Win32_NetworkAdapter Class.

Enable Method

Disable Method

Hi Danny35d!

This looks VERY promising...I'll try to test it today but 1st have to fix a certain server of mine which run into a bsod this morning. I'll give you feedback as soon as I can. Meanwhie: Thank you very very much!!!

Best Regards, Chris

Edited by cherdeg

Share this post


Link to post
Share on other sites

Okay Rudi, thank you so far. And how should, in you opinion, the whole command look like, if the Interface/Connection had the name "Local Area Connection"? Your advice quite misplaced, ...

Sorry for misplacing my answer for you... :)

When I searched for DHCP action automation I found a lot of desciptions telling, that NETSH.EXE (almost) can do anything you can do in the network properties' GUI. It's not comfortable, but powerful.

E.g. this one I use to change IP settings to DHCP:

netsh int ip set address "LAN-Verbindung" dhcp

similar lines can switch to manually specified settings for IP, mask, Gate, DNS, ...

As the "netsh[option] [option] ?" help isn't really too nice to read use google in case you'd like to make use of it -- but you already wrote that the other aproach given looks nice to you :)

Regards, Rudi.


Earth is flat, pigs can fly, and Nuclear Power is SAFE!

Share this post


Link to post
Share on other sites

cherdeg to be able to enable and disable network adapter in Vista and Server 2008 you need to use Win32_NetworkAdapter Class.

Hi Danny35d!

I use your code like this (here the part of a larger script of mine):

#include <Constants.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <String.au3>
#include <file.au3>
#include <Array.au3>

; Recognize the current system's Operation System
; ==============================================================================================
Local $OSver = @OSVersion
MsgBox(0, "OSver", $OSver)

; Disble the NIC to activate the new settings
; ==============================================================================================
; Read from the .ini-File which network connection to use
$s_interface = "Local Area Connection"

; Disable the NIC
$InfoValue = "Disabling Network Interface Card..."
_InfoGui($InfoValue)
If $OSver <> "WIN_2000" And $OSver <> "WIN_XP" And $OSver <> "WIN_2003" Then
    _NicToggleNEW($s_interface, 0)
    Sleep(2000) 
EndIf
GUIDelete()




; Function _InfoGUI to display an info about the task currently processed.
; ==============================================================================================
Func _InfoGUI($InfoValue)
    GUICreate("", 300, 100, -1, -1, $WS_Popup, $WS_EX_TOOLWINDOW, "")
    GUICtrlCreateLabel($InfoValue, 0, 45, 300, -1, $SS_Center)
    GUISetState(@SW_SHOW)
    Sleep(500)
EndFunc   ;==>_InfoGUI

; Function _NicToggleNEW to Disable and Enable a Network card using 'Shell.Application' - Parameters: $oLanConnection and $iFlag
; ==============================================================================================
;_ToggleNetworkInterface('local area connection', 0)
;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _NicToggleNEW($strNetwork, $iFlag)
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $strComputer = "localhost"

    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)

    If IsObj($colItems) Then
        For $objItem In $colItems
            If $objItem.NetConnectionID = $strNetwork Then
                If $iFlag = 0 And $objItem.NetEnabled = True Then
                    $objItem.Disable
                ElseIf $iFlag = 1 And $objItem.NetEnabled = False Then
                    $objItem.Enable
                EndIf
                ExitLoop
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
EndFunc   ;==>_NicToggleNEW

It works absolutely perfect on Vista/2009 Server; on the earlier OSses I use one of the other functions I posted here. Thank you very much!!!

If I now could get rif of the other errors showing up only in Vista/2008 Server, I was finished with my tool...maybe you could lend me a hand and a small piece of your profession, Danny35d? I'm getting several error messages like "Variable is not of type object"...

Best Regards,

Chris

Share this post


Link to post
Share on other sites

When I searched for DHCP action automation I found a lot of desciptions telling, that NETSH.EXE (almost) can do anything you can do in the network properties' GUI. It's not comfortable, but powerful.

Hi Rudi,

It's fine that you found the tool of your choice in netsh.exe. Never the less you can't enable/disable LAN connections with netsh.exe. If I set the options for my LAN connections (IP, Mask, GW, DNS, WINS) I well use netsh.exe all the time.

If I missed something or did do something the wrong way (see my commands above), please feel completely free to correct me at will.

Or just supply me with a complete and working netsh-command, e.g., to disable "Lan-Verbindung".

Regards, Chris

Share this post


Link to post
Share on other sites

It works absolutely perfect on Vista/2009 Server; on the earlier OSses I use one of the other functions I posted here. Thank you very much!!!

If I now could get rif of the other errors showing up only in Vista/2008 Server, I was finished with my tool...maybe you could lend me a hand and a small piece of your profession, Danny35d? I'm getting several error messages like "Variable is not of type object"...

Best Regards,

Chris

Try it. I took the example script from Post #6.
#include <Array.au3>
#RequireAdmin

Opt("TrayMenuMode", 1)
TraySetIcon("Shell32.dll", -150)
TraySetToolTip("QuickNIC")

Global $OSver = @OSVersion
Global $strEnable = "En&able"
Global $strDisable = "Disa&ble"
Global $colNetwork = ""
Global $msg

Func NetworkConnectionsObject()
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        Local $wbemFlagReturnImmediately = 0x10
        Local $wbemFlagForwardOnly = 0x20
        Local $strComputer = "localhost"
        $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
        $colNetwork = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    Else
        $objShell = ObjCreate("Shell.Application")
        $strNetConn = "Network Connections"
        $objCP = $objShell.Namespace(3)
        For $clsConn In $objCP.Items
            If $clsConn.Name = $strNetConn Then $colNetwork = $clsConn.GetFolder
        Next
    EndIf
    Return $colNetwork
EndFunc   ;==>NetworkConnectionsObject

Func GetNetworkNames($colNetwork)
    Dim $strNetworks
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        If IsObj($colNetwork) Then
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID <> '' Then $strNetworks &= $clsConn.NetConnectionID & '|'
            Next
        Else
            MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
        EndIf
    Else
        For $clsConn In $colNetwork.Items
            If StringInStr($clsConn.Name, "Wizard") = 0 Then
                $strNetworks = $strNetworks & $clsConn.Name & "|"
            EndIf
        Next
    EndIf
    $strNetworks = StringLeft($strNetworks, StringLen($strNetworks) - 1)
    $arrNetworks = StringSplit($strNetworks, "|")
    _ArrayDelete($arrNetworks, 0)
    _ArraySort($arrNetworks)
    Return $arrNetworks
EndFunc   ;==>GetNetworkNames

Func AddTrayItems($arrNetworks)
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        For $i = 0 To UBound($arrNetworks) - 1
            NetworkConnectionsObject()
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID = $arrNetworks[$i] Then
                    TrayCreateItem($arrNetworks[$i])
                    If $clsConn.NetEnabled = False Then
                        TrayItemSetState(-1, 1)
                    Else
                        TrayItemSetState(-1, 4)
                    EndIf
                EndIf
            Next
        Next
    Else
        For $i = 0 To UBound($arrNetworks) - 1
            For $clsConn In $colNetwork.Items
                If $clsConn.Name = $arrNetworks[$i] Then
                    TrayCreateItem($arrNetworks[$i])
                    For $clsVerb In $clsConn.verbs
                        If $clsVerb.name = $strDisable Then TrayItemSetState(-1, 1)
                        If $clsVerb.name = $strEnable Then TrayItemSetState(-1, 4)
                    Next
                EndIf
            Next
        Next
    EndIf
EndFunc   ;==>AddTrayItems

Func ToggleNetworkInterface($strNetwork)
    For $clsConn In $colNetwork.Items
        If $clsConn.Name = $strNetwork Then
            For $clsVerb In $clsConn.verbs
                If $clsVerb.name = $strDisable Then
                    $clsVerb.DoIt
                    Sleep(200)
                    Return 0
                EndIf
                If $clsVerb.name = $strEnable Then
                    $clsVerb.DoIt
                    TrayItemSetState($msg, 1)
                    Sleep(200)
                    Return 1
                EndIf
            Next
        EndIf
    Next
EndFunc   ;==>ToggleNetworkInterface

; Function _NicToggleNEW to Disable and Enable a Network card using 'Shell.Application' - Parameters: $oLanConnection and $iFlag
; ==============================================================================================
;_ToggleNetworkInterface('local area connection', 0)
;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _NicToggleNEW($strNetwork, $iFlag)
    NetworkConnectionsObject()
    If IsObj($colNetwork) Then
        For $clsConn In $colNetwork
            If $clsConn.NetConnectionID = $strNetwork Then
                If $iFlag = 0 And $clsConn.NetEnabled = True Then
                    $clsConn.Disable                    
                ElseIf $iFlag = 1 And $clsConn.NetEnabled = False Then
                    $clsConn.Enable
                EndIf
                ExitLoop
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
EndFunc   ;==>_NicToggleNEW

AddTrayItems(GetNetworkNames(NetworkConnectionsObject()))

$separator = TrayCreateItem("")
$trayabout = TrayCreateItem("About")
$trayexit = TrayCreateItem("Exit")
TraySetState()

While 1
    $msg = TrayGetMsg()

    If $msg > 0 And $msg <> $trayabout And $msg <> $trayexit Then
        $strNetworkAdapter = TrayItemGetText($msg)
        If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
            ConsoleWrite($msg & ' ' & TrayItemGetState($msg) & ' = ' & $TRAY_CHECKED & ' ' & BitAND(TrayItemGetState($msg), $TRAY_CHECKED) & @crlf)
            
            If BitAND(TrayItemGetState($msg), $TRAY_CHECKED) = $TRAY_CHECKED Then
                _NicToggleNEW($strNetworkAdapter, 0)
            Else                
                _NicToggleNEW($strNetworkAdapter, 1)                
            EndIf
        Else
            ToggleNetworkInterface($strNetworkAdapter)
        EndIf
    EndIf

    If $msg = $trayabout Then
        SplashTextOn("About...", "QuickNIC is a tool that provides a quick and easy method to toggle (enable/disable) your Network Connections." & @CRLF & @CRLF & "version 0.2b", 300, 120)
        Sleep(3500)
        SplashOff()
    EndIf

    If $msg = $trayexit Then ExitLoop
WEnd

AutoIt Scripts:NetPrinter - Network Printer UtilityRobocopyGUI - GUI interface for M$ robocopy command line

Share this post


Link to post
Share on other sites

Try it. I took the example script from Post #6.

Hi Danny35d,

It works, but it doesn't work... :)

I can run it on 2008 Server and the Network connections is listed in the tray menu - but unfortunately without the tick. Also clicking the entry doesn't switch the network connection. Could you give it another look? Thank you very much for your great efforts!!!

Regards, Chris

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

I finally got it, thanks to Danny35d.

For everybody interested, the final code looks like that:

#include <Constants.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <StaticConstants.au3>
#include <String.au3>
#include <file.au3>
#include <Array.au3>

#RequireAdmin

Global $OSver = @OSVersion
Global $strEnable = "En&able"
Global $strDisable = "Disa&ble"
Global $colNetwork = ""
Global $msg


; Recognize the current system's Operation System
; ==============================================================================================
Local $OSver = @OSVersion
; MsgBox(0, "OSver", $OSver)


; Disble the NIC to activate the new settings
; ==============================================================================================
; Read from the .ini-File which network connection to use
; $s_interface = "Local Area Connection"

$arrNetCons = _GetNetConNames(_NetConsFolderObject())
_ArrayDisplay($arrNetCons)
; Disable the NIC
If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
    $strNetCon = $arrNetCons[0]
    MsgBox(0, "NetCon on Vista/W2K8", $strNetCon)
    _NicToggleNEW($strNetCon, 0)               
Else
    $strNetCon = $arrNetCons[3]
    MsgBox(0, "NetCon on Windows", $strNetCon)
    _NicToggleOLD($strNetCon)
EndIf


; Function _InfoGUI to display an info about the task currently processed.
; ==============================================================================================
Func _InfoGUI($InfoValue)
    GUICreate("", 300, 100, -1, -1, $WS_Popup, $WS_EX_TOOLWINDOW, "")
    GUICtrlCreateLabel($InfoValue, 0, 45, 300, -1, $SS_Center)
    GUISetState(@SW_SHOW)
    Sleep(500)
EndFunc   ;==>_InfoGUI


; Function _NetConsFolderObject to find the folder containing the network connection objects
; ==============================================================================================
Func _NetConsFolderObject()
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        Local $wbemFlagReturnImmediately = 0x10
        Local $wbemFlagForwardOnly = 0x20
        Local $strComputer = "localhost"
        $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
        $colNetwork = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    Else
        $objShell = ObjCreate("Shell.Application")
        $strNetConn = "Network Connections"
        $objCP = $objShell.Namespace(3)
        For $clsConn In $objCP.Items
            If $clsConn.Name = $strNetConn Then 
            $colNetwork = $clsConn.GetFolder
            EndIf
        Next
    EndIf
    Return $colNetwork
EndFunc   ;==>_NetConsFolderObject


; Function _GetNetConNames to find the network connection objects
; ==============================================================================================
Func _GetNetConNames($colNetwork)
    Dim $strNetworks
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        If IsObj($colNetwork) Then
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID <> '' Then $strNetworks &= $clsConn.NetConnectionID & '|'
            Next
        Else
            MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
        EndIf
    Else
        For $clsConn In $colNetwork.Items
            If StringInStr($clsConn.Name, "Wizard") = 0 Then
                $strNetworks = $strNetworks & $clsConn.Name & "|"
            EndIf
        Next
    EndIf
    $strNetworks = StringLeft($strNetworks, StringLen($strNetworks) - 1)
    $arrNetworks = StringSplit($strNetworks, "|")
    _ArrayDelete($arrNetworks, 0)
    _ArraySort($arrNetworks)
    Return $arrNetworks
EndFunc   ;==>GetNetworkNames


; Function _NicToggleNEW to Disable and Enable a Network card using 'Shell.Application' - Parameters: $oLanConnection and $iFlag
; ==============================================================================================
;  _NicToggleNEW('local area connection', 0)
;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _NicToggleNEW($strNetworks, $iFlag)
    _NetConsFolderObject()
    If IsObj($colNetwork) Then
        For $clsConn In $colNetwork
            If $clsConn.NetConnectionID = $strNetworks Then
                If $iFlag = 0 And $clsConn.NetEnabled = True Then
                    $clsConn.Disable                   
                ElseIf $iFlag = 1 And $clsConn.NetEnabled = False Then
                    $clsConn.Enable
                EndIf
                ExitLoop
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
EndFunc   ;==>_NicToggleNEW


; Function _NicToggleOLD to Disable and Enable a Network card using 'Shell.Application' - Parameters: $oLanConnection and $iFlag
; ==============================================================================================
;  _NicToggleOLD('local area connection', 0)
;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _NicToggleOLD($strNetworks, $iFlag)
    For $clsConn In $colNetwork.Items
        If $clsConn.Name = $strNetworks Then
            For $clsVerb In $clsConn.verbs
                If $iFlag = 0 And $clsVerb.name = $strDisable Then
                    $clsVerb.DoIt
                    Sleep(200)
                    Return 0
                EndIf
                If $iFlag = 1 And $clsVerb.name = $strEnable Then
                    $clsVerb.DoIt
                    Sleep(200)
                    Return 1
                EndIf
            Next
        EndIf
    Next
EndFunc   ;==>_NicToggleOLD

I am sure that there are much too many includes, feel free to cleanup. Due to the fact that this is only one part of a larger script I simply copied and pasted it. Also I am sure that with a little motivation and too much spare time it would be able to merge "_NicToggleOLD" and "_NicToggleNEW" to one function - feel free.

I still have a little problem with my larger script, which I soll post in this thread. It would be great if somebody could do me the favour and look over it...

Best Regards,

Chris

Edited by cherdeg

Share this post


Link to post
Share on other sites

I know this is an old thread, but I thought I'd add some to it. I modified the code some to meet my needs, and some may find it useful.

The first iteration is an app which enumerates and displays your existing NICs and allows you to disable them individually

;======================================================================================
;
; SwitchNIC -   displays a popup with a list of currently available network cards
;               and gives you the option to enable/disable each NIC
;
; Author:       Tim Morris
;
; Credits:      Thanks to Danny35d and Cherdeg for the info from the AutoIT Forum
;               (http://www.autoitscript.com/forum/lofiversion/index.php?t72165.html)
;
;======================================================================================

#RequireAdmin
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=..\..\..\Desktop\nic.ico
#AutoIt3Wrapper_outfile=SwitchNIC.exe
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>

;AutoItSetOption ( "GUICoordMode", 1 )

Global $OSver = @OSVersion
Global $strEnable = "En&able"
Global $strDisable = "Disa&ble"
Global $colNetwork = ""
Global $msg
;Global $NICStatus

Dim $NicsFound[1][1] ; $NicsFound['NIC name']['NIC status (0=disabled)']
Dim $Checkbox[100]
Dim $Label[100]
Dim $IconFile[4]

If $OSver = "WIN_VISTA"  Then
    $IconFile[0] = 'netcenter.dll'
    $IconFile[1] = 8
    $IconFile[2] = 'netcenter.dll'
    $IconFile[3] = 17
Else
    $IconFile[0] = 'shell32.dll'
    $IconFile[1] = 10
    $IconFile[2] = 'shell32.dll'
    $IconFile[3] = 10   
EndIf

$Form1 = GUICreate("SwitchNIC 0.1", 235, 100, -1, -1)
$ButtonApply = GUICtrlCreateButton("Apply", 30, 60, 75, 25, 0)
$ButtonCancel = GUICtrlCreateButton("Cancel", 130, 60, 75, 25, 0)
GUISetState(@SW_SHOW)

_GetNetConNames(_NetConsFolderObject())

$StartingX = 25 ;default is 60
$StartingY = 20 ;default is 45
$WinHeight = 20
$WinLocation = WinGetPOS("[active]")
;_ArrayDisplay($NicsFound)

WinMove($Form1, "", $WinLocation[0], $WinLocation[1], 235, UBound($NicsFound,1) * 20 + 100, 1)
    
For $i = 0 To UBound($NicsFound,1)-1
    ;MsgBox(0, "", "$i=" & $i & " value=" & $arrNetCons[$i])
    $Checkbox[$i] = GUICtrlCreateCheckbox("", $StartingX, $StartingY, 15, 15)
    If $NicsFound[$i][1] <> 0 Then GUICtrlSetState($Checkbox[$i], $GUI_CHECKED)
    If StringLeft($NicsFound[$i][0], 5)="Local" Then 
        GUICtrlCreateIcon ( $IconFile[0], $IconFile[1], $StartingX - 20, $StartingY, 15, 15 )
        $Label[$i] = GUICtrlCreateLabel(" " & $NicsFound[$i][0], $StartingX + 20, $StartingY, 250, 17)
    ElseIf StringLeft($NicsFound[$i][0], 5)="Wirel" Then
        GUICtrlCreateIcon ( $IconFile[2], $IconFile[3], $StartingX - 20, $StartingY, 15, 15 )
        $Label[$i] = GUICtrlCreateLabel(" " & $NicsFound[$i][0], $StartingX + 20, $StartingY, 250, 17)
    Else
        $Label[$i] = GUICtrlCreateLabel($NicsFound[$i][0], $StartingX + 20, $StartingY, 250, 17)
    EndIf
    
    
    GUICtrlSetPos( $ButtonApply, $StartingX, $StartingY + 30)
    GUICtrlSetPos( $ButtonCancel, $StartingX + 100, $StartingY + 30)
    $StartingY = $StartingY + 20
Next

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit            
        Case $ButtonCancel
            Exit
        Case $ButtonApply
            Apply()
        Case Else
            
    EndSwitch
WEnd

; Apply the changes
Func Apply()
    For $i = 0 To UBound($NicsFound,1)-1
        If GUICtrlRead( $Checkbox[$i] ) = $GUI_CHECKED AND $NicsFound[$i][1] = 0 Then _NicToggle( $NicsFound[$i][0], 1 )
        If GUICtrlRead( $Checkbox[$i] ) = $GUI_UNCHECKED AND $NicsFound[$i][1] <> 0 Then _NicToggle( $NicsFound[$i][0], 0 )
    Next
    Exit
EndFunc

; Find the folder containing the network connection objects
; ==============================================================================================
Func _NetConsFolderObject()
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $strComputer = "localhost"
    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colNetwork = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    Return $colNetwork
EndFunc   ;==>_NetConsFolderObject

; Find the network connection objects
; ==============================================================================================
Func _GetNetConNames($colNetwork)
    Dim $strNetworks, $IDXname=0, $IDXstatus=0
    If IsObj($colNetwork) Then
        For $clsConn In $colNetwork
            If $clsConn.NetConnectionID <> '' Then 
                $strNetworks &= $clsConn.NetConnectionID & '|'
                ReDim $NicsFound[$IDXname+1][2]
                $NicsFound[$IDXname][0] = $clsConn.NetConnectionID
                $NicsFound[$IDXname][1] = $clsConn.NetConnectionStatus
                $IDXname = $IDXname + 1
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
    Return
EndFunc   ;==>GetNetworkNames

; Disable and Enable a Network card
; ==============================================================================================
;  _NicToggle('local area connection', [0=disable, 1=enable])
Func _NicToggle($strNetworks, $iFlag)
    If $OSver = "WIN_VISTA"  Then
        _NetConsFolderObject()
        If IsObj($colNetwork) Then
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID = $strNetworks Then
                    ;If $iFlag = 0 And $clsConn.NetEnabled = True Then
                    If $iFlag = 0 And $clsConn.NetConnectionStatus <> 0 Then
                        ;msgbox(0,"", "Disabling " & $clsConn.NetConnectionID)
                        $clsConn.Disable
                    ;ElseIf $iFlag = 1 And $clsConn.NetEnabled = False Then
                    ElseIf $iFlag = 1 And $clsConn.NetConnectionStatus = 0 Then
                        ;msgbox(0,"", "Enabling " & $clsConn.NetConnectionID)
                        $clsConn.Enable
                    EndIf
                    ExitLoop
                EndIf
            Next
        Else
            MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
        EndIf
    Else ; Windows 2000 & XP
        $objShell = ObjCreate("Shell.Application")
        $strNetConn = "Network Connections"
        $objCP = $objShell.Namespace(3)
        For $clsConn In $objCP.Items
            If $clsConn.Name = $strNetConn Then
            $colNetwork = $clsConn.GetFolder
            EndIf
        Next
        For $clsConn In $colNetwork.Items
            If $clsConn.Name = $strNetworks Then
                For $clsVerb In $clsConn.verbs
                    If $iFlag = 0 And $clsVerb.name = $strDisable Then
                        $clsVerb.DoIt
                        Sleep(200)
                        Return 0
                    EndIf
                    If $iFlag = 1 And $clsVerb.name = $strEnable Then
                        $clsVerb.DoIt
                        Sleep(200)
                        Return 1
                    EndIf
                Next
            EndIf
        Next
    EndIf
EndFunc   ;==>_NicToggle

-- Tim

Share this post


Link to post
Share on other sites

Part 2:

This script adds an icon to the system tray which shows your NICs, and allows you to enable/disable them from there. This has very little changed from the tray script posted earlier, but that script seemed to be backwards in some places. When clicking on an interface, it would do the opposite of what I expected. It could have just been me :P Anyway, here's my version:

;======================================================================================
;
; SwitchNIC-Tray -  displays a systray app which allows you to switch between to NICs
;
; Author:       Tim Morris
;
; Credits:      Thanks to Danny35d and Cherdeg for the info from the AutoIT Forum
;               (http://www.autoitscript.com/forum/lofiversion/index.php?t72165.html)
;
;======================================================================================

#include <Constants.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
;~ #include <WindowsConstants.au3>
;~ #include <StaticConstants.au3>
;~ #include <String.au3>
;~ #include <file.au3>
#include <Array.au3>
#RequireAdmin

Opt("TrayMenuMode", 1)
TraySetIcon("Shell32.dll", -150)
TraySetToolTip("SwitchNIC-Tray")

Global $OSver = @OSVersion
Global $strEnable = "En&able"
Global $strDisable = "Disa&ble"
Global $colNetwork = ""
Global $msg

Func NetworkConnectionsObject()
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        Local $wbemFlagReturnImmediately = 0x10
        Local $wbemFlagForwardOnly = 0x20
        Local $strComputer = "localhost"
        $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
        $colNetwork = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    Else
        $objShell = ObjCreate("Shell.Application")
        $strNetConn = "Network Connections"
        $objCP = $objShell.Namespace(3)
        For $clsConn In $objCP.Items
            If $clsConn.Name = $strNetConn Then $colNetwork = $clsConn.GetFolder
        Next
    EndIf
    Return $colNetwork
EndFunc   ;==>NetworkConnectionsObject

Func GetNetworkNames($colNetwork)
    Dim $strNetworks
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        If IsObj($colNetwork) Then
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID <> '' Then $strNetworks &= $clsConn.NetConnectionID & '|'
            Next
        Else
            MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
        EndIf
    Else
        For $clsConn In $colNetwork.Items
            If StringInStr($clsConn.Name, "Wizard") = 0 Then
                $strNetworks = $strNetworks & $clsConn.Name & "|"
            EndIf
        Next
    EndIf
    $strNetworks = StringLeft($strNetworks, StringLen($strNetworks) - 1)
    $arrNetworks = StringSplit($strNetworks, "|")
    _ArrayDelete($arrNetworks, 0)
    _ArraySort($arrNetworks)
    Return $arrNetworks
EndFunc   ;==>GetNetworkNames

Func AddTrayItems($arrNetworks)
    If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
        For $i = 0 To UBound($arrNetworks) - 1
            NetworkConnectionsObject()
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID = $arrNetworks[$i] Then
                    TrayCreateItem($arrNetworks[$i])
                    If $clsConn.NetEnabled = False Then
                        TrayItemSetState(-1, 4)
                    Else
                        TrayItemSetState(-1, 1)
                    EndIf
                EndIf
            Next
        Next
    Else
        For $i = 0 To UBound($arrNetworks) - 1
            For $clsConn In $colNetwork.Items
                If $clsConn.Name = $arrNetworks[$i] Then
                    TrayCreateItem($arrNetworks[$i])
                    For $clsVerb In $clsConn.verbs
                        If $clsVerb.name = $strDisable Then TrayItemSetState(-1, 1)
                        If $clsVerb.name = $strEnable Then TrayItemSetState(-1, 4)
                    Next
                EndIf
            Next
        Next
    EndIf
EndFunc   ;==>AddTrayItems

Func ToggleNetworkInterface($strNetwork)
    For $clsConn In $colNetwork.Items
        If $clsConn.Name = $strNetwork Then
            For $clsVerb In $clsConn.verbs
                If $clsVerb.name = $strDisable Then
                    $clsVerb.DoIt
                    Sleep(200)
                    Return 0
                EndIf
                If $clsVerb.name = $strEnable Then
                    $clsVerb.DoIt
                    TrayItemSetState($msg, 1)
                    Sleep(200)
                    Return 1
                EndIf
            Next
        EndIf
    Next
EndFunc   ;==>ToggleNetworkInterface

; Function _NicToggleNEW to Disable and Enable a Network card using 'Shell.Application' - Parameters: $oLanConnection and $iFlag
; ==============================================================================================
;_ToggleNetworkInterface('local area connection', 0)
;  $iFlag = 0 Disable network interface
;  $iFlag = 1 Enable network interface
Func _NicToggleNEW($strNetwork, $iFlag)
    NetworkConnectionsObject()
    If IsObj($colNetwork) Then
        For $clsConn In $colNetwork
            If $clsConn.NetConnectionID = $strNetwork Then
                If $iFlag = 0 And $clsConn.NetEnabled = True Then
                    $clsConn.Disable                   
                ElseIf $iFlag = 1 And $clsConn.NetEnabled = False Then
                    $clsConn.Enable
                EndIf
                ExitLoop
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
EndFunc   ;==>_NicToggleNEW

$trayabout = TrayCreateItem("About")
$trayexit = TrayCreateItem("Exit")
$separator = TrayCreateItem("")
AddTrayItems(GetNetworkNames(NetworkConnectionsObject()))
TraySetState()

While 1
    $msg = TrayGetMsg()

    If $msg > 0 And $msg <> $trayabout And $msg <> $trayexit Then
        $strNetworkAdapter = TrayItemGetText($msg)
        If $OSver <> "WIN_2000"  And $OSver <> "WIN_XP"  And $OSver <> "WIN_2003"  Then
            ConsoleWrite($msg & ' ' & TrayItemGetState($msg) & ' = ' & $TRAY_CHECKED & ' ' & BitAND(TrayItemGetState($msg), $TRAY_CHECKED) & @crlf)
           
            If BitAND(TrayItemGetState($msg), $TRAY_CHECKED) = $TRAY_CHECKED Then
                _NicToggleNEW($strNetworkAdapter, 1)
            Else               
                _NicToggleNEW($strNetworkAdapter, 0)               
            EndIf
        Else
            ToggleNetworkInterface($strNetworkAdapter)
        EndIf
    EndIf

    If $msg = $trayabout Then
        SplashTextOn("About...", @CRLF & "SwitchNIC-Tray allows you to quickly switch between network connections." & @CRLF & @CRLF & "10/16/2008" & @CRLF & @CRLF & "v0.1" & @CRLF, 300, 120, -1, -1, 1, "", 10)
        Sleep(3500)
        SplashOff()
    EndIf

    If $msg = $trayexit Then ExitLoop
WEnd

-- Tim

Share this post


Link to post
Share on other sites

... And finally, this script switches between 2 defined networks, and displays them in the systray with a more user-friendly label. In my office, we have 2 different networks (the "Brown" and the "Green"). With this, I simply set my wired NIC to the Brown, and the wireless NIC to the Green.

To modify for your needs, just change the array variables $Network1 and $Network2. Element 0 is the GUI handle, so don't set it to anything. Element 1 is the user-friendly label, and element 2 is the actual name of the NIC (from My Network Places).

Enjoy!

;======================================================================================
;
; SwitchNetworks -  displays a systray app which allows you to switch between to NICs
;
; Author:       Tim Morris
;
; Credits:      Thanks to Danny35d and Cherdeg for the info from the AutoIT Forum
;               (http://www.autoitscript.com/forum/lofiversion/index.php?t72165.html)
;
;======================================================================================

#include <Constants.au3>
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
;#include <WindowsConstants.au3>
;#include <StaticConstants.au3>
;#include <String.au3>
;#include <file.au3>
;#include <Array.au3>
#RequireAdmin

Opt("TrayMenuMode", 1)
TraySetIcon("Shell32.dll", -150)
TraySetToolTip("SwitchNetwork")

Global $OSver = @OSVersion
Global $strEnable = "En&able"
Global $strDisable = "Disa&ble"
Global $colNetwork = ""
Global $msg

Dim $NicsFound[1][1] ; $NicsFound['NIC name']['NIC status (0=disabled)']
Dim $Network1[3] ; $Network1[1]=systray label for network 1, $network1[2]=network 1 NIC device
Dim $Network2[3] ; $Network2[1]=systray label for network 2, $network2[2]=network 2 NIC device
$Network1[1] = "Brown"
$Network1[2] = "Local Area Connection"
$Network2[1] = "Green"
$Network2[2] = "Wireless Network Connection"
;$Network2[2] = "Local Area Connection 2"

; Find the folder containing the network connection objects
; ==============================================================================================
Func _NetConsFolderObject()
    Local $wbemFlagReturnImmediately = 0x10
    Local $wbemFlagForwardOnly = 0x20
    Local $strComputer = "localhost"
    $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2")
    $colNetwork = $objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    Return $colNetwork
EndFunc   ;==>_NetConsFolderObject

; Find the network connection objects
; ==============================================================================================
Func _GetNetConNames($colNetwork)
    Dim $strNetworks, $IDXname=0, $IDXstatus=0
    If IsObj($colNetwork) Then
        For $clsConn In $colNetwork
            If $clsConn.NetConnectionID <> '' Then 
                $strNetworks &= $clsConn.NetConnectionID & '|'
                ReDim $NicsFound[$IDXname+1][2]
                $NicsFound[$IDXname][0] = $clsConn.NetConnectionID
                $NicsFound[$IDXname][1] = $clsConn.NetConnectionStatus
                $IDXname = $IDXname + 1
            EndIf
        Next
    Else
        MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
    EndIf
    Return
EndFunc

Func AddTrayItems($arrNetworks)
    $Network1[0]=TrayCreateItem($Network1[1])
    $Network2[0]=TrayCreateItem($Network2[1])
    For $i = 0 To UBound($NicsFound, 1) - 1
        If $NicsFound[$i][0] = $Network2[2] Then
            If $NicsFound[$i][1] = 0 Then
                TrayItemSetState($Network2[0], 4)
            Else
                TrayItemSetState($Network2[0], 1)
            EndIf
        ElseIf $NicsFound[$i][0] = $Network1[2] Then
            If $NicsFound[$i][1] = 0 Then
                TrayItemSetState($Network1[0], 4)
            Else
                TrayItemSetState($Network1[0], 1)
            EndIf
        EndIf
    Next
EndFunc   ;==>AddTrayItems

Func _NicToggle($NetworkEnable, $NetworkDisable)
    If $OSver = "WIN_VISTA"  Then
        _NetConsFolderObject()
        If IsObj($colNetwork) Then
            For $clsConn In $colNetwork
                If $clsConn.NetConnectionID = $NetworkEnable[2] Then
                        $clsConn.Enable
                        TrayItemSetState($NetworkEnable[0], 1)
                ElseIf $clsConn.NetConnectionID = $NetworkDisable[2] Then
                    $clsConn.Disable
                    TrayItemSetState($NetworkDisable[0], 4)
                EndIf
            Next
        Else
            MsgBox(0, "WMI Output", "No WMI Objects Found for class: " & "Win32_NetworkAdapter")
        EndIf
    Else ; Windows 2000/XP/2003
        $objShell = ObjCreate("Shell.Application")
        $strNetConn = "Network Connections"
        $objCP = $objShell.Namespace(3)
        For $clsConn In $objCP.Items
            If $clsConn.Name = $strNetConn Then
            $colNetwork = $clsConn.GetFolder
            EndIf
        Next
        For $clsConn In $colNetwork.Items           
            If $clsConn.Name = $NetworkEnable[2] Then
                For $clsVerb In $clsConn.verbs
                    If $clsVerb.name = $strEnable Then
                        $clsVerb.DoIt
                        TrayItemSetState($NetworkEnable[0], 1)
                        Sleep(200)
                    EndIf
                Next
            ElseIf $clsConn.Name = $NetworkDisable[2] Then
                For $clsVerb In $clsConn.verbs
                    If $clsVerb.name = $strDisable Then
                        $clsVerb.DoIt
                        TrayItemSetState($NetworkDisable[0], 4)
                        Sleep(200)
                    EndIf
                Next
            EndIf
        Next
    EndIf
EndFunc   ;==>_NicToggle

; ========================================================================================
; Begin Main Script
; ========================================================================================

$trayabout = TrayCreateItem("About")
$trayexit = TrayCreateItem("Exit")
$separator = TrayCreateItem("")

_NetConsFolderObject()
AddTrayItems(_GetNetConNames(_NetConsFolderObject()))
TraySetState()

While 1
    $msg = TrayGetMsg()

    If $msg > 0 And $msg <> $trayabout And $msg <> $trayexit Then
        $ChangeNet = TrayItemGetText($msg)
        ;ConsoleWrite($msg & ' ' & TrayItemGetState($msg) & ' = ' & $TRAY_CHECKED & ' ' & BitAND(TrayItemGetState($msg), $TRAY_CHECKED) & @crlf)                                
        If $ChangeNet = $Network2[1] Then
            _NicToggle($Network2, $Network1)
        ElseIf $ChangeNet = $Network1[1] Then
            _NicToggle($Network1, $Network2)
        EndIf
    EndIf

    If $msg = $trayabout Then
        SplashTextOn("About...", @CRLF & "SwitchNetwork allows you to quickly switch between network connections." & @CRLF & @CRLF & "10/16/2008" & @CRLF & @CRLF & "v0.1" & @CRLF, 300, 120, -1, -1, 1, "", 10)
        Sleep(4000)
        SplashOff()
    EndIf

    If $msg = $trayexit Then Exit
WEnd

-- Tim

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0