ToggleNic, and DuMeter

Post your working scripts, libraries and tools
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

ToggleNic, and DuMeter

24 Oct 2015, 15:22

Please take note!
Running this script, will switch off you're internet connection right away when you're browser is not running!

On first run the script will make a file NetAccess.acc and add Firefox/IE/Edge/Chrome as default apps.
Right or double click the tray icon and select "Configure Appplist" to add new apps to the list.

Once this was a simple .bat file running below commands. Hooked to the windows taskbar as two buttons so I could easily enable/disable my network interface.
@Echo Off
netsh.exe interface set interface name=Ethernet admin=disable
Or
@Echo Off
netsh.exe interface set interface name=Ethernet admin=enable

But clicking buttons is something I try to do as few as possible. So here is ToggleNic, a script that lets you define a list with applications that on start up, will enable internet connection by requesting a ip from a dhcp server. Or it disables network connection to the internet, by releasing the ip when no more allowed applications exist. So you need to be behind a router or receive you're ip dynamically. Which is probably how most machines connect these day's.

This app is tested on windows10 and AutoHotkey version v1.1.29.01. I'm not sure about older Windows versions though.

_____________________________ Gui's and icons _____________________________

Image

_____________________________________________________________________

Download ToggleNic v2.0.6.exe x64 below:
ToggleNic.7z
ToggleNic v2.0.6.exe x64
AHK v1.1.29.01
(440.57 KiB) Downloaded 44 times
The Script Version 2.0.6:

Code: Select all

; ToggleNic V2.0.6.
; Made with aid of AutoGui IDE, ThanX guys!

#NoEnv
#SingleInstance off
#NoTrayIcon
DetectHiddenWindows on
SetWorkingDir %A_ScriptDir%
SetBatchLines -1
ListLines off

; --------------------------------------- Script Functions ---------------------------------------

DisableNet() {
    static LAN := "192.168", LoopBack := "127.0", APIPA := "169.254"

    ; When the ip address - on the first adapter - is not localhost or Automatic Ip addressing.
    ; Network must be swiched off.
    if (!InStr(A_IPAddress1, LoopBack) || !InStr(A_IPAddress1, APIPA)) {
    
        Menu, tray, Icon, % IconFile, % IconNoNetwork
        Menu, tray, Tip, % "No Network"
        
        Run, %ComSpec% /c "Ipconfig /release Ethernet*", , Hide
        
        ; Wait Until the ip on the first physicaladaper is released.
        while (InStr(A_IPAddress1, LAN))
            sleep 10
            
        Menu, tray, Icon, % IconFile, % IconDisabled
        Menu, tray, Tip, % "Disabled"

    } else { ; When the ip address is localhost or AIPA. Only change tray icon/ToolTip accordingly.
    
        Menu, tray, Icon, % IconFile, % IconDisabled
        Menu, tray, Tip, % "Disabled"
    }
}

EnableNet() {
    static IpAdapter1, LAN := "192.168", LoopBack := "127.0", APIPA := "169.254"

    ; A one time save of the Ip address for the first physical device on the system.
    ; Used when the machine receives it's IP directly from the ISP.
    IF (!IpAdapter1)
        IpAdapter1 := A_IPAddress1
 
    ; When a local or publick IP address is assigned.
    if (!InStr(A_IPAddress1, LAN) || !InStr(A_IPAddress1, IpAdapter1)) {
        
        Menu, tray, Icon, % IconFile, % IconNoNetwork
        Menu, tray, Tip, % "No Network"
        
        Run, %ComSpec% /c "Ipconfig /renew Ethernet*", , Hide
        
        ; Wait for any of these IP addresses to change. Thus there is a connection.
        while (InStr(A_IPAddress1, LoopBack) || InStr(A_IPAddress1, APIPA))
            sleep 10
        
        Menu, tray, Icon, % IconFile, % IconEnabled
        Menu, tray, Tip, % LocalAreaNetwork > 0 ? WanIp : ipv4
        
    } else { ; But if there isn't one assigned. Only change tray icon/ToolTip accordingly.
    
        Menu, tray, Icon, % IconFile, % IconEnabled
        Menu, tray, Tip, % LocalAreaNetwork > 0 ? WanIp : ipv4
    }
}

QueryNic() {

    DevInfo := Wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true")._NewEnum()
    while DevInfo[i] {
        Mac := i.MACAddress, Name := i.Name, DeviceID := i.DeviceID
    }
    
    for i in wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index=" DeviceID) {
        Ip := i.IpAddress[0], DNSServer1 := i.DNSServerSearchOrder[0], DNSServer2 := i.DNSServerSearchOrder[1]
        DNSServer := InStr(DNSServer1, "192.168") ? DNSServer2 : DNSServer1
    }
    Return {"ipv4": Ip, "WanIp": GetWanIp(DNSServer), "DNSServer": DNSServer, "NetworkCard": Name, "DeviceID": DeviceID, "Mac": Mac }
}

/* Not Used anymore
; Disable the default network device. The device is toggled on/off by its index number stored in variable DeviceID.

DisableNic(DeviceID) {
    Wmi.ExecMethod("Win32_NetworkAdapter.DeviceID='" DeviceID "'","Disable")
    while ((Ip := QueryNic1()) || Ip > 0) {
        sleep 50
} }

; Enable the default network device.

EnableNic(DeviceID, pExit := 0) {
    Wmi.ExecMethod("Win32_NetworkAdapter.DeviceID='" DeviceID "'","Enable")
    if (pExit = 1) {
        return
    }
    while (!(Ip := QueryNic1()) || Ip = 0) {
        sleep 50
} }

QueryNic1(GetInfo = 0) {

    if (GetInfo = 0) {
        Try {
            for i in wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index=" DeviceID)
                Ip := i.IpAddress[0]
        }
        return Ip
    }
    else if (GetInfo = 1) {
        DevInfo := Wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true")._NewEnum()
        while DevInfo[i] {
            Mac := i.MACAddress, Name := i.Name, DeviceID := i.DeviceID ;, DeviceID%A_index% := DeviceID, NetworkCard%A_index% := Name
        }
        for i in wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index=" DeviceID) {
            Ip := i.IpAddress[0], DNSServer1 := i.DNSServerSearchOrder[0]
            , DNSServer2 := i.DNSServerSearchOrder[1], DNSServer := InStr(DNSServer1, "192.168") ? DNSServer2 : DNSServer1
        }
        Return {"ipv4": Ip, "WanIp": GetWanIp(DNSServer), "DNSServer": DNSServer, "NetworkCard": Name, "DeviceID": DeviceID, "Mac": Mac }
    }
}

*/

GetWanIp(pDnsIp) {
    
    Local
    
    ClipBrdOld := Clipboard
    
    WaitConnectISP:
    Clipboard := ""
    RunWait, %ComSpec% /c "ping -n 1 -r 1 %pDnsIp% | clip", , Hide

    Loop, parse, % Clipboard, `n, `r
    {
        if (A_Index = 4) {
        
            if (!(WanIp := Trim(SubStr(A_LoopField, 12), " `t`n`r"))) {
                Gosub, WaitConnectISP
                break
            }
            else if (WanIp > 0) {
                Clipboard := ClipBrdOld  
                
               
            }
        }
    }
     return WanIp
}

GetNetSpeed() {

    local MIB_IF_ROW2, IfIndex
    
    ; Create interface structure and use the default network device.
    VarSetCapacity(MIB_IF_ROW2, 1368, 0)
    DllCall("iphlpapi\GetBestInterface", "Ptr", 0, "Ptr*", IfIndex)
    NumPut(IfIndex, &MIB_IF_ROW2+8, "UInt")
    NumPut(&MIB_IF_ROW2+1256, &MIB_IF_ROW2+1352), NumPut(&MIB_IF_ROW2+1320, &MIB_IF_ROW2+1360) ; InUcastOctets/OutUcastOctets


    ; Get/Refresh structure data.
    DllCall("iphlpapi\GetIfEntry2", "Ptr", &MIB_IF_ROW2)
    
    ; Return bytes In/Out
    return {1: NumGet(NumGet(&MIB_IF_ROW2+1352), "Int64"), 2: NumGet(NumGet(&MIB_IF_ROW2+1360), "Int64")}
}

/* About AHKGroupEX()

 ahk_group is great for checking multiple windows.
 What I miss is a feature to also remove apps from the ahk_group.
 This function allows you to create a window group that can both add And
 remove. In it's essence, it creates and returns a array made from the
 GuiNames in AddApp*
 
 Command to add:
  AHKGroupEX(, "MyGui1", "MyGui2" .. . )

 Command to remove:
  AHKGroupEX(1, "MyGui1", "MyGui2" .. . )
 
*/

AHKGroupEX(Remove:="", AddApp*) {
    Static Apps := []
    
    if (Remove) {
        Apps.RemoveAt(Remove, Apps.Length(Apps[Remove]))
    }
    else if (Apps.Length() < 1) {
        i := 1
    
        ParseFile:
        Loop, parse, % FileOpen(A_ScriptDir "\NetAccess.acc", 0).read(), `n, `r`n
        {
            If (A_LoopField) {
                Apps[(i++)] := Trim(A_LoopField, " `t`r`n"), Size := A_Index
            } else {
                Continue, ParseFile
    }   }   }
    else if (AddApp.Length() > 0) {
        for i, App in AddApp {
            Apps.InsertAt(Apps.Length()+i, "ahk_exe " App)
            FileAppend, % "ahk_exe " App "`n", %A_ScriptDir%\NetAccess.acc
    } }
    Return Apps
}

/* About WindowExist()
 
 Input parameter should the array created by AHKGroupEX().
 Returns the Window handle if successful.
 
  Command:
   WindowExist(Apps)
   
*/

WindowExist(A) {
    SetWinDelay 1
    for i, v in A {
        if (hWmd := WinExist(v)) {
            return hWmd
    }   }
}

/* About ToggleAutoToggle()

 ToggleAutoToggle is a function label for the toggle option in the script context menu.
 But the function is also called on startup when auto-toggle is off.
 
*/

ToggleAutoToggle(StartUp := 0) {
    Global
    
    local i
    if (StartUp = 1) {
        ShellMessage(1, "StartUp")
        Menu, tray, Tip, %WanIp%`nAutoToggle = Off
        Menu, tray, Icon, % IconFile, % IconEnabled
        
    } else {
    
        i := (ToggleNew = ToggleOff), i > 0 ? (ToggleNew := ToggleOn, ToggleOld := ToggleOff, tt := WanIp "`nAutoToggle = Off", OnMessage(MsgID,""), AutoToggle := 0, EnableNet()) : (ToggleNew := ToggleOff, ToggleOld := ToggleOn, tt := WanIp, OnMessage(MsgID, "ShellMessage"), AutoToggle := 1, (i := WindowExist(Applist)) < 1 ? DisableNet())
        
        if (i = 0)
            Gui hide
            
        Menu, tray, Tip, % tt
        Menu, tray, rename, %ToggleOld%, %ToggleNew%
        IniWrite, %AutoToggle%, % A_ScriptDir "\Settings.ini", Settings, AutoToggle
}   }

/* About GuiUpdate()

 When parm1 in List* is a object, input format should be as following.
 Parm1 is the object holding all Gui's.
 Object1 holding 2 GUi's could look like:
  Object1: {1: "VarGuiName1", 2: "VarGui2Name"}

 Parm2 and greater are the objects holding the parameters.
 Where Object2 are the parameters belonging to Gui1 and object3 are the parameters for Gui2, Obj4 for Gui3 and so on.
 Objects could look like:
  Object2, with one parameter looks like: {1: "Parm1"}				<-- Gui1
  Object3, with two parameters looks like: {1: "Parm1", 2: "Parm2"}	<-- Gui2

 Command to update two GUI's:
  			Gui's								 Parameters
  GuiUpdate({1: "VarGuiName1", 2: "VarGuiName2"}, {1: "Parm1"}, {1: "Parm1", 2: "Parm2"})
  
 Or Update a single gui from a Array:
  GuiUpdate(GuiNameObj1, ParmObj2)

 And when parm1 in object List* is a string, then it's value should be the name of the gui to update.
 
 Command:
  GuiUpdate("MyGuiName", "Parm1", "Parm2",.. . . .)
 
*/

GuiUpdate(List*) {

    if (IsObject(List[1])) {
        for indx, GuiId in List[1] {
            for i, P in List[indx+1] {
                if (P = "Submit") {
                    Gui % GuiId ":" P, NoHide
                }
                else {
                    Gui % GuiId ":" P
        }   }   }
        
    } else {
    
        for i, P in List {
            if (!GuiId) {
                GuiId := P
            }
            else if (GuiId) {
                if (P = "Submit") {
                    Gui % GuiId ":" P, NoHide
                }
                else {
                    Gui % GuiId ":" P
}   }   }   }   }

/* About GuiControl()

 GuiControl() is a bit simpler to use then GuiUpdate()
 You can use any of the first 3 parameters to you're liking, in the same way
 as in command GuiControl. Input type is preferable a string but can be a var
 , mind the double quotes.
 
 Command:
  GuiControl(, "aID", "SomeParameter") or GuiControl("Move", "aID", "x10")
 
 Or Just Ignore the first 3 parmaters and insert a Object or Array on parameter 4
 following the example given in the GuiUpdate() function.
 
 Command:
  GuiControl(,,, MyArray)
  GuiControl(,,, {1: Gui1, 2: Gui2, 3: Gui3}, {1: Parm1, 2: Parm2, 3: Parm3}, {1: Parm1}, {1: Parm1, 2: Parm2})
  
 Returns ErrorLevel.

*/

GuiControl(cmd:="", CtrlId:="", Parm:="", A*) {
    SetControlDelay -1
    Critical
    
    if IsObject(A[1]) {
        for i, CtrlId in A[1] {
            for indx, Parm in A[i+1] {
            
                if (A[i+1].Length() = 1) {
                    GuiControl, , %CtrlId%, %Parm%
                    E := ErrorLevel
                }
                else if (A[i+1].Length() = 2) {
                    if (indx = 1) {
                        cmd :=  Parm
                   }     
                    else if (indx = 2) {
                        GuiControl, %cmd%, %CtrlId%, %Parm%
                        E := ErrorLevel
    }    }   }    }   }
    
    else if (!cmd && Parm) {
        GuiControl, , %CtrlId%, %Parm%
        E := ErrorLevel
        
    } Else if (cmd && !parm) {
        GuiControl, %cmd%, %CtrlId%
     E := ErrorLevel
     
    } Else if (cmd && parm) {
        GuiControl, %cmd%, %CtrlId%, %P%
        E := ErrorLevel
    }
    return E
}

/* About LoadLibraries()

 Loads all module handles in LibFiles* and returns them in a array.
 
  Command:
   LoadLibraries("*.dll", "*.dll")

*/

LoadLibraries(LibFiles*) {
    Modules := []
    
    for i, LibFiles in LibFiles {
        if (InStr(LibFiles, "gdiplus")) {
            VarSetCapacity(Size, A_PtrSize = 8 ? 24 : 16, 0), Size := Chr(1)
            DllCall("gdiplus\GdiplusStartup", A_PtrSize ? "UPtr*" : "uint*", pTo, A_PtrSize ? "UPtr" : "UInt", &Size, Ptr, 0)
            Modules[i, 1] := DllCall("LoadLibrary", "str", "gdiplus"), Modules[i, 2] := pTo, Modules[i, 3] := SubStr(LibFiles, 1, InStr(LibFiles, ".")-1)
        } else {
            Modules[i, 1] := DllCall("LoadLibrary", "Str", LibFiles, "Ptr"), Modules[i, 2] := 0, Modules[i, 3] := SubStr(LibFiles, 1, InStr(LibFiles, ".")-1)
        } }
    return Modules
}

/* About FreeLibraries()

 
 Frees all handles in Modules* from memory.
 
  Command:
   FreeLibraries("*.dll", "*.dll")
   
*/

FreeLibraries(Modules*) {

    For i, Modules in Modules
        DllCall("FreeLibrary", "Ptr", Modules[i, 1])
    Return 0
}

/* About CreateFocusRec()
 
 Draws a transparent but color
 
 Parmaters:
  1: The handle for the control to draw on.
  2: The handle for the window to which the control belongs to.
  3: The colour for the layer.

*/

CreateFocusRec(CtrlhWnd, WinHwnd, Clr) {
    Critical

    SetControlDelay -1
    
    GuiControlGet c, Pos, %CtrlhWnd%

    Gui, GdiLayer: -Caption +E0x80000 +LastFound +AlwaysOnTop hwndhGdiLayer
    Gui, GdiLayer: Show, NA

    DllCall("SetParent", "uint", hGdiLayer, "uint", WinHwnd)
    
    ; Rectangle structure, only need x and y here
    VarSetCapacity(Rect, 8)
    NumPut(cX, Rect, 0, "UInt"), NumPut(cY, Rect, 4, "UInt")

    ; Bitmap structure. Aplha RGB -> 32bits -> Per Pixel
    VarSetCapacity(Bitmap, 40, 0)
    NumPut(40, Bitmap, 0, "uint"), NumPut(cW, Bitmap, 4, "uint")
    NumPut(cH, Bitmap, 8, "uint"), NumPut(1, Bitmap, 12, "ushort")
    NumPut(32, Bitmap, 14, "ushort"), NumPut(0, Bitmap, 16, "uInt")
    
    ; Use x64 or win32 pointers?
    Ptr := A_PtrSize ? "UPtr" : "UInt"
    PtrA := A_PtrSize ? "UPtr*" : "Uint*"
    
    ; Create Mem Bitmap.
    dc := DllCall("GetDC", Ptr, CtrlhWnd, "Ptr")
    hbm := DllCall("CreateDIBSection", Ptr, dc, Ptr, &Bitmap, "uint", 0, PtrA, 0, Ptr, 0, "uint", 0, "Ptr")
    hdc := DllCall("CreateCompatibleDC", Ptr, dc)
    obm := DllCall("SelectObject", Ptr, hdc, Ptr, hbm)
    DllCall("gdiplus\GdipCreateFromHDC", Ptr, hdc, PtrA, G)
    DllCall("gdiplus\GdipSetSmoothingMode", Ptr, G, "int", 4)
    
    ; Use Drawing tools.
    DllCall("gdiplus\GdipCreateSolidFill", "UInt", Clr, PtrA, pBrush)
    DllCall("gdiplus\GdipFillRectangle", Ptr, G, Ptr, pBrush, "float", 0, "float", 0, "float", cW, "float", cH)
    DllCall("gdiplus\GdipDeleteBrush", Ptr, pBrush)

    ; Update the layered window.
    DllCall("UpdateLayeredWindow", Ptr, hGdiLayer, Ptr, 0, Ptr, &Rect, "int64*", cW|cH<<32, Ptr, hdc, "int64*", 0, "uint", 0, "UInt*", 0x1FF0000, "uint", 2)

    ; Free Memory.
    DllCall("SelectObject", Ptr, hdc, Ptr, obm)
    DllCall("DeleteObject", Ptr, hbm)
    DllCall("DeleteDC", Ptr, hdc), DllCall("DeleteDC", Ptr, dc)
    DllCall("gdiplus\GdipDeleteGraphics", Ptr, G)
}

; ------------------------------- Windows messages functions and related -------------------------------

WM_MouseMove(wParam, lParam, msg, hWnd) {
    
    local i, mX, mY
    
    static handle, hwndGui, Higlight, ObjGuiMn, ObjCtrls, FocusRec := 0 ;, hWnd := Format("0x{1:x}", h)
    
    ObjGuiMn := {1: "ContextMenu", 2: "Apps"}, pGui1 := {1: "Destroy", 2: "-Disabled"}, pGui2 := {1: "+AlwaysOnTop", 2: "-Disabled"}
    ObjCtrls := {1: {1: "hGdiLayer", 2: hGdiLayer}, 2: {1: "hBtnApplistClose", 2: hBtnApplistClose, 3: "0x50E81123"}, 3: {1: "hBttnAddApp", 2: hBttnAddApp, 3: "0x40777777"}, 4: {1: "hBttnExit", 2: hBttnExit, 3: "0x40777777"}, 5: {1: "hBtnOk", 2: hBtnOk, 3: "0x40777777"}, 6: {1: "hBtnClose",  2: hBtnClose, 3: "0x50E81123"}}
    
    For i, v in [hDU, hDuUpFrq, hAppList] {
        if (hWnd = v) {
            hWndGui := v
    }   }

    if (hwnd = hMenuDel && !Higlight) {
        Higlight := 1
        Gui ContextMenu:font,  cffffff
        GuiControl, Font, RemApp
    }
    else if (hWnd = hCntxMn && Higlight = 1) {
        Higlight := 0
        Gui ContextMenu:font, ce4e4c4
        GuiControl, Font, RemApp           
    }
    else if (hwnd = hCntxMn) {
        mX := lParam & 0xFFFF, mY := lParam >> 16
        i := ((mX < 2 || mX > 170) || (mY < 2 || mY > 22)), i ? (GuiUpdate(ObjGuiMn, pGui1, pGui2))
    }

    if (!GetKeyState("Lbutton", "D")) {
    
        for i, in ObjCtrls {
            if (hwnd = ObjCtrls[i, 2] && FocusRec = 0) {
                FocusRec := 1, CtrlID := ObjCtrls[i, 1], CtrlHwnd := ObjCtrls[i, 2], CrtlColor := ObjCtrls[i, 3]
                CreateFocusRec(CtrlHwnd, WinExist(), CrtlColor)

            }
            else if (hwnd = hwndGui && FocusRec = 1) {
               FocusRec := 0
               GuiUpdate({1: "GdiLayer"}, {1: "Destroy"}), FocusRec := 0
}   }   }   }

Wm_LbuttonDown(wParam, lParam, msg, hWnd) {
    ;Static hWnd := Format("0x{1:x}", h)
    
    if (hwnd = hGdiLayer) {
        GuiUpdate("GdiLayer", "Destroy")
        MouseGetPos, , , , hWnd, 2

        For k, v in Object("hBtnOk", "ButtonOke", "hBtnClose", "DuUpFrqClose", "hBtnApplistClose", "AppListClose"
                         , "hBttnAddApp", "AddApp", "hBttnExit", "AppListClose", "hMenuDel", "RemApp") {
            
            if (hWnd = %k%) {
                gosub % v
        }   }
        Return
    }

    For k, v in Object("hDU", "DU_", "hDuUpFrq", "GuiUpFrq_", "hAppList", "Aplst_") {
    
        If (hwnd = %k%) {
        
            FadeInOut(hWnd, "On")
            PostMessage, 0xA1, 2, , , % "ahk_id" %k%
            FadeInOut(hwnd, "off")
            
            WinGetPos, X, Y, , , % "ahk_id" %k%
            vX := v "X", %vX% := X, vY := v "Y", %vY% := Y
            IniWrite, % X, % A_ScriptDir "\Settings.ini", Coordinates, % vX
            IniWrite, % Y, % A_ScriptDir "\Settings.ini", Coordinates, % vY
}   }   }

/* About FadeInOut()
 
 FadeInOut() is a helper function for Wm_LbuttonDown().
 BUt when called whit only the window handle, that window will be faded in and out again.
 parameters:
  1: The handle of the window to fade.
  2: If the window is dragged Use "On" to fade out. Use "Off" when is dragging stoped, to fade in again.
  3: How much percentage to fade the window out. Default is 25% of it's original transparency.
     This Only have to be used with the "On" parameter and if some other transparency value then the default want to be set..
     Because - fading back - caclulates back to it's original transparency, not the value faded out. Using this whith
     the "Off" parameter will be discarded.

Commands:
 FadeInOut(hWnd, "On", 35) - FadeInOut(hWnd, "On") - FadeInOut(hwnd, "off") - FadeInOut(hWnd,, 35)
*/

FadeInOut(hWnd, Dragg := "", Pcrt = 25) {
    SetBatchLines -1
    static TransOut, TransparencyOld, Transparency := 0, Handles := {}, HCnt := 0

    if (HCnt = 0)
        HCnt += 1, Handles := {(HCnt): hwnd}
    
    if (Handles[HCnt] != hwnd)
       HCnt += 1, Handles := {(HCnt): hwnd}
        
    if (Dragg = "On") {
    
        WinGet, Transparency, Transparent, ahk_id %hWnd%
        TransparencyOld := Transparency
        TransOut := (TransparencyOld - (TransparencyOld/100)*Pcrt)
        
        Loop {
            If (A_TickCount >= WaitNextTick) {
                WaitNextTick := A_TickCount+5
                WinSet, Transparent, % Transparency -= 5, ahk_id %hWnd%
                
                If (Transparency <= TransOut)
 
                    break
        }   }
        
        return
        
    } else if (Dragg = "Off") {
    
        Loop {
            If (A_TickCount >= WaitNextTick) {
                WaitNextTick := A_TickCount+5
                WinSet, Transparent, % Transparency += 5, ahk_id %hWnd%
                
                If (Transparency >= TransparencyOld) {
                
                    Transparency := 0
                    break
        }   }   }
        return
    }
    
    If (Transparency = 0) {
        
        WinGet, Transparency, Transparent, ahk_id %hWnd%
        TransparencyOld := Transparency
        TransOut := (TransparencyOld - (TransparencyOld/100)*Pcrt)
        
        Loop {
            If (A_TickCount >= WaitNextTick) {
                WaitNextTick := A_TickCount+25
                WinSet, Transparent, % Transparency += 15, ahk_id %hWnd%
                
                ; If (Transparency >= 250){
                If (Transparency >= TransOut){
                    ;WinSet, Transparent, Off, ahk_id %hWnd%
                    break
        }   }   }
    } else {
        Loop {
            If (A_TickCount >= WaitNextTick) {
                WaitNextTick := A_TickCount+25
                WinSet, Transparent, % Transparency -= 15, ahk_id %hWnd%
                
                If (Transparency <= TransparencyOld)
                    break
        }   }  }
    return
}

ShellMessage(wParam, lParam := 0) {
    global

    Static CheckLease, NetState := 1,  LAN := "192.168"
   
    ; CHeck to see if the OS didn't somwhere request a new IP but when it did, disable network.
    
    if (!InStr(A_IPAddress1, LAN) && !WindowExist(Applist) && lParam = 0) {
        DisableNet()
    }
    
    ; HSHELL_WINDOWCREATED if wParam = 1
    ; ENables the nic when a application in Object Applist starts.
    ; Ghange menu lables from Enable to Disable.
    ; Enables DuMeter if it was switched on before.
 
    else if (wParam = 1 && WindowExist(Applist) && NetState = 0 || lParam = "StartUp") {
    
        EnableNet(), NetState := 1
        
        if (DuOn = 1 && !Running) {
            Running := 1
            
            if (DuMnLbl != "Disable DU Meter") {
            
                Gui, Show, % "x" Du_X "y" Du_Y "NA", DuOsd
                menu, DuMeter, rename,  % (DuMnLblNxt := "Enable DU Meter"), % (DuMnLbl := "Disable DU Meter")
                Settimer, UpdateDU, % UpdFrq
                ;gosub, UpdateDU
                
            } else {
            
                Gui, Show, % "x" Du_X "y" Du_Y "NA", DuOsd
                Settimer, UpdateDU, % UpdFrq
                ;gosub, UpdateDU
        } }
        
        ; A one time check to see if we still have the correct public ip address.
        
        if (!CheckLease) {
            CheckLease := GetWanIp(DNSServer)
            if (CheckLease != WanIp) {
                Menu, tray, Tip, % (WanIp := CheckLease)
                IniWrite, % WanIp, % A_ScriptDir "\Settings.ini", Settings, WanIp
    }   }   }

    ; HSHELL_WINDOWDESTROYED if wParam = 2
    ; Disables the nic when last running application in Object Applist terminates and the device is On.
    ; Hide DuMeter gui since it's not needed.
    ; Changes menu lables accourding to nic status.
    
    else if (wParam = 2 && !WindowExist(Applist) && NetState) {
        DisableNet(), Running := NetState := 0
        Gui, hide
        Settimer, UpdateDU, Off
}   }

Wm_MouseLeave(wParam, lParam, msg, h) {
    hWnd := Format("0x{1:x}", h)
    if (hwnd = hLv) {
        LV_Modify(RowNr, "-Select")
        ControlSend, , {tab}, ahk_id %hWnd%
}   }

TrayNotify(wParam, lParam) {
    if (lParam = 0x203 && !WinExist("Applist")) {
        Gosub, allowedApps  
    }
    else if (lParam = 0x203 && WinExist("Applist")) {
        Gosub, AppListClose
}   }


if (!A_IsAdmin) {
        Try {
        if (A_IsCompiled) {
            Run, *RunAs "%A_ScriptFullPath%"
        } else {
            Run, *RunAs "%A_AhkPath%" /ErrorStdOut "%A_ScriptFullPath%"
        }
    } Catch ThisError {
        MsgBox % ThisError
    }
    ExitApp
}

Menu, tray, Icon
Menu, tray, Icon, deskadp.dll, -100
;Menu, tray, Icon, pnidui.dll, 13

Global IconOpenDu, DuOn,hGdiLayer,IconEnabled,IconNoNetwork,LocalAreaNetwork,WanIp,ipv4,DNSServer,DeviceID,RowNr,RowTxT,MsgID,AutoToggle,ToggleOld,ToggleNew:=ToggleOff,ToggleOff:="Disable AutoToggle",ToggleOn:="Enable AutoToggle",UpdFrq:=1000,IconFile:="pnidui.dll",Applist:=[],Wmi:=ComObjGet("winmgmts:"),DuMnLbl := "Enable DU Meter",DuMnLblNxt := "Disable DU Meter"

UnitIn:="KB",UnitOut:="KB",Download:="0.00",Upload:="0.00",BIn:=BOut:=counter:=0,SldrPos:=1000,SS_CENTERIMAGE:=0x200,Modules:=LoadLibraries("Iphlpapi", "gdiplus"), DU_x := DU_y := Aplst_X := Aplst_Y := "Center"

ReadIni:
Loop, parse, % FileOpen(A_ScriptDir "\Settings.ini", 0).read(), `n, `r
{
    if (InStr(A_LoopField, "["))
        continue, ReadIni
    i := SubStr(A_LoopField, 1, InStr(A_LoopField, "=")-1), %i% := SubStr(A_LoopField, InStr(A_LoopField, "=")+1)
}

; -------------------------- GuiContext/Tray-menu and GUI for D/U Meter -------------------------

Menu, tray, NoStandard
Menu, DuMeter, add, % DuMnLbl, DuMeter
Menu, DuMeter, add, Change Update Interval, GuiUpdateInt
Menu, DuMeter, add, Change Size, DuMeterScale
Menu, DuMeter, add
Menu, DuMeter, add, Double click tray opens DuMeter, TrayOpenDuMeter
Menu, DuMeter, Check, Double click tray opens DuMeter
Menu, DuMeter, UnCheck, Double click tray opens DuMeter

Menu, tray, add, DU Meter, :DuMeter
Menu, tray, add
Menu, tray, add, Configure AppList, allowedApps

Menu, tray, add, % (AutoToggle = 1 || AutoToggle = "") = 1 ? (ToggleNew := ToggleOff, AutoToggle := 1) : (ToggleNew := ToggleOn, AutoToggle = 0), ToggleAutoToggle
GuiControl +g, ToggleAutoToggle()

Menu, tray, add
Menu, tray, add, Network Connections, Connections
Menu, tray, add, Windows Firewall, Firewall
Menu, tray, add, Firewall Advanced, FirewallAdv
Menu, tray, add
Menu, tray, add, Restart script, Restart
Menu, tray, add, Exit, CloseScript

; Create Gui for D/U Meter.
DuGui:

; Saves the nane of the label when called, so it can be used below.
if (!ThisLabel && A_ThisLabel = "DuGui")
    ThisLabel := A_ThisLabel
 
; Set variables for Small or Bigg size.
DuSize <= 0 ? (s := "9", h := "28", w1 := "90", w2 := "52", w3 := "20") : (s := "10", h := "34", w1 := "103", w2 := "58", w3 := "25")

Gui, +LastFound +AlwaysOnTop +owner -Caption +Border HwndhDU
Gui, margin, 2, 2
Gui, font, s%s% w600 ce4e4c4 q5
Gui, color, 0x080808
Gui, add, Progress, xm ym h%h% w%w1% hWndhProgress +Background0x1f1f1f +0x8000000
Gui, add, text, xm+1 ym section BackgroundTrans, D:
Gui, add, text, xs BackgroundTrans, U:
Gui, add, text, ys w%w2% BackgroundTrans center section vBytesIn, %Download%
Gui, add, text, xs wp BackgroundTrans center vBytesOut, %Upload%
Gui, add, text, ys w%w3% BackgroundTrans section vUnitIn, %UnitIn%
Gui, add, text, xs wp BackgroundTrans vUnitOut, %UnitOut%
WinSet, Transparent, 180, ahk_id %hDU%

; Re-Enable the gui when size was changed.
if (ThisLabel = "DuGui") {

    ThisLabel := ""
    Gui, Show, % "x" DU_x "y" DU_y "NA", DuOsd
    Settimer, UpdateDU, % UpdFrq

    Return
}

If (!FileExist(A_ScriptDir "\Settings.ini")) {

    ; Get icons for Win-10, Win-7 or Win-8.
    i := InStr(A_OSVersion, 10), i ? (IconDisabled := 1, IconEnabled := 13, IconNoNetwork := 14) : A_OSVersion = "Win_7" ? (IconDisabled:=26, IconEnabled := 28, IconNoNetwork := 29) : (IconDisabled := 2, IconEnabled:= 15, IconNoNetwork := 16), i:="", List := 1

    Gui GetDevices:Default
    Gui GetDevices:+LastFound +owner1 +owndialogs +AlwaysOnTop +LabelChooseDev -MinimizeBox -MaximizeBox
    Gui GetDevices:add, DropDownList, x12 y12 w345 h125 vList +AltSubmit Choose1
   
    EnumDev := ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true")._NewEnum()
    while EnumDev[i] {
        Name := i.Name, DeviceID := i.DeviceID, DeviceID%A_index% := DeviceID, NetworkCard%A_index% := Name
        if (Name) {
            GuiControl, , List, %Name%||
    }   }
   
    Gui GetDevices:add, Button, x367 y12 w96 h19 gChooseDevOk, Ok
    Gui GetDevices:show, , Choose a default network adapter
    Return

    ChooseDevClose:
    ChooseDevEscape:
    FileDelete, % A_ScriptDir "\Settings.ini"
    ExitApp
   
    ChooseDevOk:
    GuiUpdate("GetDevices", "Submit")
    GuiControl, +AltSubmit, List
    NetworkCard := NetworkCard%List%, DeviceID := DeviceID%List%
    IniWrite, %NetworkCard%, % A_ScriptDir "\Settings.ini", Settings, NetworkCard
    IniWrite, %DeviceID%, % A_ScriptDir "\Settings.ini", Settings, DeviceID
   
    GuiUpdate({1: "GetDevices", 2: "1"}, {1: "Destroy"}, {1: "Default"})
   
    for i, v in QueryNic() {
        IniWrite, % v, % A_ScriptDir "\Settings.ini", Settings, % i
       
        if (i = "ipv4" && InStr(v, "192.168")) {
            LocalAreaNetwork := 1
    }   }
   
    for i, v in ["LocalAreaNetwork", "IconDisabled", "IconEnabled", "IconNoNetwork"] {
        If (v) {
            IniWrite, % %v%, % A_ScriptDir "\Settings.ini", Settings, %v%
    }   }
   
    If (!FileExist(A_ScriptDir "\NetAccess.acc")) {
        for i, v in ["ahk_exe Firefox.exe","ahk_exe Iexplore.exe","ahk_exe Chrome.exe","ahk_exe MicrosoftEdge.exe"] {
            FileAppend, %v%`n, %A_ScriptDir%\NetAccess.acc
    }   }
   
    List:=i:=v:=EnumDevices:=""
    Gosub, RegHookAndMsgs
    Return
}

RegHookAndMsgs:
AppList := AHKGroupEX(), DllCall("RegisterShellHookWindow", UInt, A_ScriptHwnd)
MsgID := DllCall("RegisterWindowMessage", Str, "SHELLHOOK")

AutoToggle < 1 ? (ToggleAutoToggle("1")) : ((WindowExist(AppList)) > 0 ? ShellMessage(1, "StartUp") : ShellMessage(2), OnMessage(MsgID,"ShellMessage"))

OnMessage(0x201, "Wm_LbuttonDown"), OnMessage(0x2A3, "Wm_MouseLeave"), OnMessage(0x404, "TrayNotify"), OnMessage(0x200, "Wm_MouseMove")
return

; Right click the DU window will show a context menu. The tray menu in this case.
GuiContextMenu:
menu, tray, show, % A_GuiX, % A_GuiY
return

; -------------------------------------------- Du Meter ------------------------------------------

; Show/Hide the D/U Meter Gui.
DuMeter:
if (DuMnLbl != "Disable DU Meter") {
    Gui, Show, % "x" DU_x "y" DU_y "NA", DuOsd
    menu, DuMeter, rename,  % DuMnLbl, % DuMnLblNxt
    DuMnLbl := "Disable DU Meter", DuMnLblNxt := "Enable DU Meter", Running := DuOn := 1
    Settimer, UpdateDU, % UpdFrq
    gosub, UpdateDU
} else {
    Settimer, UpdateDU, Off
    Gui hide
    menu, DuMeter, rename,  % DuMnLbl, % DuMnLblNxt
    DuMnLbl := "Enable DU Meter", DuMnLblNxt := "Disable DU Meter", PerfData := Running := DuOn := 0
}
IniWrite, % DuOn, % A_ScriptDir "\Settings.ini", Settings, DuOn
return

DuMeterScale:
IniWrite, % DuSize <= 0 ? (DuSize := 1) : (DuSize := 0), % A_ScriptDir "\Settings.ini", Settings, DuSize
Settimer, UpdateDU, Off
Gui, 1:Destroy
Gosub, DuGui
Return

TrayOpenDuMeter:
Return

; D/U Meter counter data.
UpdateDU:
if (GetKeyState("Lbutton", "D") && WinActive("ahk_id" hDu) || WinActive("ahk_id" hDuUpFrq) || WinActive("ahk_id" hAppList))
    return

if (Start && !End) {

    DllCall("QueryPerformanceCounter", "Int64*", End)
    BytesInOUt := GetNetSpeed(), BInEnd := BytesInOUt[1], BOutEnd := BytesInOUt[2]

    If (!CountDownActive)
        OldDownload := Download, OldUpload := Upload
 
    mls := ((End-Start)/Frq)/1000, Start := End := 0
    KBIn := ((BInEnd-BInStart)/1000)/(mls*0.9765625)
    KBOut :=((BOutEnd-BOutStart)/1000)/(mls*0.9765625)
   
    ; Since units and format are in KiloBytes, moving decimal point 3 space to the left to get MegaByte.
    KBIn >= 1024 ? (Download := KBIn/1000 UnitIn := "MB") : (Download := KBIn, UnitIn := "KB")
    KBOut >= 1024 ? (Upload := KBOut/1000, UnitOut := "MB") : (Upload := KBOut, UnitOut := "KB")

    if (Download >= 1.00) {
   
        if (CountDownActive && Download > 2.00) {
            CountDownActive := NextPeriod := ""
        }
        else if (IdlPeriodOn) {
            IdlPeriodOn := NetworkTrafic := 0
            Settimer, UpdateDU, % UpdFrq
            ;Gosub, UpdateDU
        }
       
        if (!CountDownActive) {
            GuiControl(,,,{1: "BytesIn", 2: "BytesOut", 3: "UnitIn", 4: "UnitOut"}, {1: Round(Download, 2)}, {1: Round(Upload, 2)}, {1: UnitIn}, {1: UnitOut})
    }   }
    else if (Download < 1.00 ) {
           
        if (!IdlPeriodOn) {
            CountDownActive := 1
            GuiControl(,,,{1: "UnitIn", 2: "UnitOut"}, {1: UnitIn}, {1: UnitOut})
            A_TickCount >= NextPeriod ? (IdleTimer := 60000, NextPeriod := A_TickCount+IdleTimer) : (IdleTimer := NextPeriod-A_TickCount, GuiControl(,,,{1: "BytesIn", 2: "BytesOut"}, {1: OldDownload := Round(OldDownload - (Round(OldDownload/2, 2)), 2)}, {1: OldUpload := Round(OldUpload - (Round(OldUpload/2, 2)), 2)}))
           
            If (!NetworkTrafic) ; UnitIn := UnitOut := "KB",
                GuiControl(,,,{1: "BytesIn", 2: "BytesOut", 3: "UnitIn", 4: "UnitOut"}, {1: "0.00"}, {1: "0.00"}, {1: UnitIn}, {1: UnitOut}), NetworkTrafic := 1

           
            if ((IdleTimer//1000) <= 1 && CountDownActive) {
                GuiControl(,,,{1: "BytesIn", 2: "BytesOut"}, {1: "- - -"}, {1: "- - -"}), IdlPeriodOn := 1, IdleTimer := CountDownActive := 0
                SetTimer, UpdateDU, 5000
}   }   }   }

if (!Start) {
    DllCall("QueryPerformanceFrequency", "Int64*", Frq), DllCall("QueryPerformanceCounter", "Int64*", Start)
    BytesInOUt := GetNetSpeed(), BInStart := BytesInOUt[1], BOutStart := BytesInOUt[2], Frq //= 1000

}
return

GuiUpdateInt:
SldrPos := UpdFrq, TransClr := 0x222222 ; TransClr := 0x060606
WinSet, TransColor, %TransClr%, "UpdateInterval"

Gui DuUpFrq:+LastFound +hWndhDuUpFrq +AlwaysOnTop +owner1 -Caption +Border
Gui DuUpFrq:margin, 2, 2
Gui DuUpFrq:font, s8 w700 ce4e4c4 q5, lucon
Gui DuUpFrq:color, 0x262626
Gui DuUpFrq:Add, button, x-1 y-1 w0 h0 +Default vBtn1
Gui DuUpFrq:add, Progress, xm ym w481 h61 vBck hWndhProgress +Background0x141414 +0x8000000   
Gui DuUpFrq:Add, Text, x0 y0 w441 h15 vStr +%SS_CENTERIMAGE% +Center +TransColor +BackgroundTrans, % SldrPos " Ms" ; Info
Gui DuUpFrq:Add, Text, x+27 y4 w13  h13 Center gDuUpFrqClose hwndhBtnClose +TransColor +0x800200, X ; Button
Gui DuUpFrq:Add, Text, x17 y20 w35 h30 vBtnOk gButtonOke hwndhBtnOk -Transparent +TransColor +Center +0x800200, OK  ; Button
Gui DuUpFrq:add, slider, x60 yp h30 w400 vSldrPos gSldrEvents Range500-3000 Line50 +TickInterval500 +AltSubmit +hwndhSldr +Background +TabStop +E0x8 +0x800000, %UpdFrq%

Gui DuUpFrq:Show, h65 w485, UpdateInterval
WinSet, Transparent, 210, % "ahk_id" hDuUpFrq
Return

; Get chosen interval from slider.
SldrEvents:
Gui, submit, nohide
GuiControl, , Str, % SldrPos " Ms"
UpdFrqOld := UpdFrq, SldrPosOld := SldrPos, UpdFrq := SldrPos
UpdFrqOld < UpdFrq ? (SldrMoved := UpdFrq-UpdFrqOld) : (SldrMoved := UpdFrqOld-UpdFrq)

if (A_GuiEvent < 8) { 
    for i, k in ["LEFT", "RIGHT", "UP", "DOWN", "WHEELUP", "WHEELDOWN", "PGUP", "PGDN", "HOME", "END"] {
        while (GetKeyState(k))    {
            KeyWait % %k%
            ControlFocus, ahk_class msctls_trackbar321
            ControlSend, ahk_class msctls_trackbar321, {Tab down}{Tab up}, ahk_id %hDuUpFrq%
            ControlFocus, ahk_class Static1
}   }  }
Gui, submit, nohide
return

ButtonOke:
Gui, Submit, NoHide:
IniWrite, %UpdFrq%, % A_ScriptDir "\Settings.ini", Settings, UpdFrq
Gui DuUpFrq:Destroy
Gui 1:-Disabled

If (DuOn = 1) {
    Settimer, UpdateDU, %UpdFrq%
    gosub, UpdateDU
}
return

DuUpFrqGuiEscape:
DuUpFrqClose:
GuiUpdate({1: "DuUpFrq", 2: "1"}, {1: "Destroy"}, {1: "-Disabled"})
return

; ------------------------------------- Gui to add/remove apps -------------------------------------

; ListView to configure allowed applications
allowedApps:
if (WinExist("Applist")) {
    Gosub, AppListClose
    Return
}

      
ClipBrdOld := Clipboard, Clipboard := A_IconNumber
Menu, tray, Icon, deskadp.dll, -100

Gui Apps:Default
Gui Apps:+LastFound +AlwaysOnTop +owner1 -Caption +Border hWndhAppList
Gui Apps:color, 0x080808
Gui Apps:font
Gui Apps:font, s9 w600 ce4e4c4 q5, Lucida Console
Gui Apps:add, Picture, xm ym h16 w16 +AltSubmit icon1, deskadp.dll
Gui Apps:add, Text, x+m, Applist
Gui Apps:add, Text, x+153 y5 w13  h13 gAppListClose hWndhBtnApplistClose +0x800200 Center, X ; Button
Gui Apps:add, ListView, x13 y40 w240 h190 Section +Background0x202020 gLVSubroutine vAppList hWndhLv -hdr, AppList

For i, App in Applist
    LvSize := LV_Add("", SubStr(App, 9)), i := ""
GuiControl +AltSubmit, AppList

Gui Apps:add, Text, xs w115 h20 +Section hWndhBttnAddApp vBttn gAddApp +0x200 +border Center, Add App ; Button
Gui Apps:add, Text, ys wp hp hWndhBttnExit gAppListClose +0x200 +border Center, Exit ; Button
Gui Apps:Show, x%Aplst_X% y%Aplst_Y% w266 h269, Applist
WinSet, Transparent, 220, % "ahk_id " hAppList
;WinSet, TransColor, 0x6e6e6e 200
Menu, tray, Icon, % IconFile, % Clipboard
Clipboard := ClipBrdOld, ClipBrdOld := ""
return
 
LVSubroutine:
Gui, Submit, NoHide

if (A_guiEvent = "RightClick") { ; && A_EventInfo >= 1) {
    RowNr := A_EventInfo
    LV_GetText(RowTxT, A_EventInfo)
    s := StrLen(" Delete: " RowTxT)*8.5
    if (RowTxT != "" && RowTxT != "AppList") {
        CoordMode, Mouse, Screen
        Gui Apps:+Disabled
        Gui ContextMenu:Default
        Gui ContextMenu:+LastFound +AlwaysOnTop +owner1 -Caption HwndhCntxMn
        Gui ContextMenu:margin, 1, 1
        Gui ContextMenu:font, s9 w600 ce4e4c4 q5, Lucida Console ;, Sitka Small
        Gui ContextMenu:color, 0x080808
        Gui ContextMenu:add, text, xm+10 ym+2 h20 w%s% +section +0x200 vRemApp gRemApp HwndhMenuDel, % " Delete: " RowTxT
        MouseGetPos, mX, mY
        Gui ContextMenu:show, % "x" mX-5 "y" mY-5 "w" s+20 "h" 26, ContextMenu
        WinSet, Transparent, 230, % "ahk_id " hCntxMn
}   }

LV_Modify(A_EventInfo, "-Select")
ControlSend, , {tab}, ahk_id %hLv%
Gui, Submit, NoHide
return

; Add new app to the list.
AddApp:
GuiUpdate("Apps", "hide")
FileSelectFile, App, M3, C:\, ,*.exe
GuiUpdate("Apps", "Default", "Show", "Submit", "+AlwaysOnTop")

Loop, parse, App, `n
{
    if (A_Index >= 2) {
        AppList := AHKGroupEX(0, A_LoopField)
        LV_Add((LvSize+=1), SubStr(AppList[LvSize], 9))
}   }

return

; Delete app from list.
RemApp:
GuiUpdate({1: "GdiLayer", 2: "ContextMenu", 3: "Apps"}, {1: "Destroy"}, {1: "Destroy"}, {1: "-Disabled", 2: "Default", 3: "+AlwaysOnTop"})

LV_Delete(RowNr), Applist := AHKGroupEX(RowNr), LvSize -= 1

if (FileExist("NetAccess.acc"))
    FileDelete, NetAccess.acc
 
For i, App in Applist
    FileAppend, %App%`n, %A_ScriptDir%\NetAccess.acc
  
GuiUpdate("Apps", "Submit")
return

AppsGuiEscape:
AppListClose:
GuiUpdate({1: "Apps", 2: "1"}, {1: "-Disabled", 2: "Default", 3: "Submit", 4: "Destroy"}, {1: "Default"})
return

; --------------------------------- Launch windows console applets ---------------------------------

; Start Control Panel\Network and Internet\Network Connections.
Connections:
Run % A_WinDir "\explorer.exe shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}\0\::{7007ACC7-3202-11D1-AAD2-00805FC1270E}"
return

; Start Control Panel\All Control Panel Items\Windows Defender Firewall.
Firewall:
Run % A_WinDir "\explorer.exe shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}\0\::{4026492F-2F69-46B8-B9BF-5654FC07E423}"
return

; Start Windows firewall mmc snap-in
FirewallAdv:  
Run % A_WinDir "\system32\wf.msc"
return
 
; --------------------------------------- End script session ---------------------------------------

; Start a new instance.
Restart:
SetTitleMatchMode, 1

if ((hwnd := WinExist("AutoGUI ")) && A_ThisLabel != "DuMeterScale") {
    if (hwnd != WinActive())
        WinActivate, ahk_id %hwnd%
    Send ^s
}

SkipSave:

if (A_IsCompiled) {
    Run *RunAs "%A_ScriptFullPath%" /restart
} else {
    Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
}

; Close script instance.
~Esc & Alt::
Exit:
CloseScript:
FreeLibraries(Modules)
ExitApp
Script Version 2.0.6 without empty lines, comments and new line feeds starting with tabs and spaces:

Code: Select all

#NoEnv
#SingleInstance off
#NoTrayIcon
DetectHiddenWindows on
SetWorkingDir %A_ScriptDir%
SetBatchLines -1
ListLines off
DisableNet() {
static LAN := "192.168", LoopBack := "127.0", APIPA := "169.254"
if (!InStr(A_IPAddress1, LoopBack) || !InStr(A_IPAddress1, APIPA)) {
Menu, tray, Icon, % IconFile, % IconNoNetwork
Menu, tray, Tip, % "No Network"
Run, %ComSpec% /c "Ipconfig /release Ethernet*", , Hide
while (InStr(A_IPAddress1, LAN))
sleep 10
Menu, tray, Icon, % IconFile, % IconDisabled
Menu, tray, Tip, % "Disabled"
} else {
Menu, tray, Icon, % IconFile, % IconDisabled
Menu, tray, Tip, % "Disabled"
}
}
EnableNet() {
static IpAdapter1, LAN := "192.168", LoopBack := "127.0", APIPA := "169.254"
IF (!IpAdapter1)
IpAdapter1 := A_IPAddress1
if (!InStr(A_IPAddress1, LAN) || !InStr(A_IPAddress1, IpAdapter1)) {
Menu, tray, Icon, % IconFile, % IconNoNetwork
Menu, tray, Tip, % "No Network"
Run, %ComSpec% /c "Ipconfig /renew Ethernet*", , Hide
while (InStr(A_IPAddress1, LoopBack) || InStr(A_IPAddress1, APIPA))
sleep 10
Menu, tray, Icon, % IconFile, % IconEnabled
Menu, tray, Tip, % LocalAreaNetwork > 0 ? WanIp : ipv4
} else {
Menu, tray, Icon, % IconFile, % IconEnabled
Menu, tray, Tip, % LocalAreaNetwork > 0 ? WanIp : ipv4
}
}
QueryNic() {
DevInfo := Wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true")._NewEnum()
while DevInfo[i] {
Mac := i.MACAddress, Name := i.Name, DeviceID := i.DeviceID
}
for i in wmi.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index=" DeviceID) {
Ip := i.IpAddress[0], DNSServer1 := i.DNSServerSearchOrder[0], DNSServer2 := i.DNSServerSearchOrder[1]
DNSServer := InStr(DNSServer1, "192.168") ? DNSServer2 : DNSServer1
}
Return {"ipv4": Ip, "WanIp": GetWanIp(DNSServer), "DNSServer": DNSServer, "NetworkCard": Name, "DeviceID": DeviceID, "Mac": Mac }
}
GetWanIp(pDnsIp) {
Local
ClipBrdOld := Clipboard
WaitConnectISP:
Clipboard := ""
RunWait, %ComSpec% /c "ping -n 1 -r 1 %pDnsIp% | clip", , Hide
Loop, parse, % Clipboard, `n, `r
{
if (A_Index = 4) {
if (!(WanIp := Trim(SubStr(A_LoopField, 12), " `t`n`r"))) {
Gosub, WaitConnectISP
break
}
else if (WanIp > 0) {
Clipboard := ClipBrdOld
}
}
}
return WanIp
}
GetNetSpeed() {
local MIB_IF_ROW2, IfIndex
VarSetCapacity(MIB_IF_ROW2, 1368, 0)
DllCall("iphlpapi\GetBestInterface", "Ptr", 0, "Ptr*", IfIndex)
NumPut(IfIndex, &MIB_IF_ROW2+8, "UInt")
NumPut(&MIB_IF_ROW2+1256, &MIB_IF_ROW2+1352), NumPut(&MIB_IF_ROW2+1320, &MIB_IF_ROW2+1360)
DllCall("iphlpapi\GetIfEntry2", "Ptr", &MIB_IF_ROW2)
return {1: NumGet(NumGet(&MIB_IF_ROW2+1352), "Int64"), 2: NumGet(NumGet(&MIB_IF_ROW2+1360), "Int64")}
}
AHKGroupEX(Remove:="", AddApp*) {
Static Apps := []
if (Remove) {
Apps.RemoveAt(Remove, Apps.Length(Apps[Remove]))
}
else if (Apps.Length() < 1) {
i := 1
ParseFile:
Loop, parse, % FileOpen(A_ScriptDir "\NetAccess.acc", 0).read(), `n, `r`n
{
If (A_LoopField) {
Apps[(i++)] := Trim(A_LoopField, " `t`r`n"), Size := A_Index
} else {
Continue, ParseFile
}   }   }
else if (AddApp.Length() > 0) {
for i, App in AddApp {
Apps.InsertAt(Apps.Length()+i, "ahk_exe " App)
FileAppend, % "ahk_exe " App "`n", %A_ScriptDir%\NetAccess.acc
} }
Return Apps
}
WindowExist(A) {
SetWinDelay 1
for i, v in A {
if (hWmd := WinExist(v)) {
return hWmd
}   }
}
ToggleAutoToggle(StartUp := 0) {
Global
local i
if (StartUp = 1) {
ShellMessage(1, "StartUp")
Menu, tray, Tip, %WanIp%`nAutoToggle = Off
Menu, tray, Icon, % IconFile, % IconEnabled
} else {
i := (ToggleNew = ToggleOff), i > 0 ? (ToggleNew := ToggleOn, ToggleOld := ToggleOff, tt := WanIp "`nAutoToggle = Off", OnMessage(MsgID,""), AutoToggle := 0, EnableNet()) : (ToggleNew := ToggleOff, ToggleOld := ToggleOn, tt := WanIp, OnMessage(MsgID, "ShellMessage"), AutoToggle := 1, (i := WindowExist(Applist)) < 1 ? DisableNet())
if (i = 0)
Gui hide
Menu, tray, Tip, % tt
Menu, tray, rename, %ToggleOld%, %ToggleNew%
IniWrite, %AutoToggle%, % A_ScriptDir "\Settings.ini", Settings, AutoToggle
}   }
GuiUpdate(List*) {
if (IsObject(List[1])) {
for indx, GuiId in List[1] {
for i, P in List[indx+1] {
if (P = "Submit") {
Gui % GuiId ":" P, NoHide
}
else {
Gui % GuiId ":" P
}   }   }
} else {
for i, P in List {
if (!GuiId) {
GuiId := P
}
else if (GuiId) {
if (P = "Submit") {
Gui % GuiId ":" P, NoHide
}
else {
Gui % GuiId ":" P
}   }   }   }   }
GuiControl(cmd:="", CtrlId:="", Parm:="", A*) {
SetControlDelay -1
Critical
if IsObject(A[1]) {
for i, CtrlId in A[1] {
for indx, Parm in A[i+1] {
if (A[i+1].Length() = 1) {
GuiControl, , %CtrlId%, %Parm%
E := ErrorLevel
}
else if (A[i+1].Length() = 2) {
if (indx = 1) {
cmd :=  Parm
}
else if (indx = 2) {
GuiControl, %cmd%, %CtrlId%, %Parm%
E := ErrorLevel
}    }   }    }   }
else if (!cmd && Parm) {
GuiControl, , %CtrlId%, %Parm%
E := ErrorLevel
} Else if (cmd && !parm) {
GuiControl, %cmd%, %CtrlId%
E := ErrorLevel
} Else if (cmd && parm) {
GuiControl, %cmd%, %CtrlId%, %P%
E := ErrorLevel
}
return E
}
LoadLibraries(LibFiles*) {
Modules := []
for i, LibFiles in LibFiles {
if (InStr(LibFiles, "gdiplus")) {
VarSetCapacity(Size, A_PtrSize = 8 ? 24 : 16, 0), Size := Chr(1)
DllCall("gdiplus\GdiplusStartup", A_PtrSize ? "UPtr*" : "uint*", pTo, A_PtrSize ? "UPtr" : "UInt", &Size, Ptr, 0)
Modules[i, 1] := DllCall("LoadLibrary", "str", "gdiplus"), Modules[i, 2] := pTo, Modules[i, 3] := SubStr(LibFiles, 1, InStr(LibFiles, ".")-1)
} else {
Modules[i, 1] := DllCall("LoadLibrary", "Str", LibFiles, "Ptr"), Modules[i, 2] := 0, Modules[i, 3] := SubStr(LibFiles, 1, InStr(LibFiles, ".")-1)
} }
return Modules
}
FreeLibraries(Modules*) {
For i, Modules in Modules
DllCall("FreeLibrary", "Ptr", Modules[i, 1])
Return 0
}
CreateFocusRec(CtrlhWnd, WinHwnd, Clr) {
Critical
SetControlDelay -1
GuiControlGet c, Pos, %CtrlhWnd%
Gui, GdiLayer: -Caption +E0x80000 +LastFound +AlwaysOnTop hwndhGdiLayer
Gui, GdiLayer: Show, NA
DllCall("SetParent", "uint", hGdiLayer, "uint", WinHwnd)
VarSetCapacity(Rect, 8)
NumPut(cX, Rect, 0, "UInt"), NumPut(cY, Rect, 4, "UInt")
VarSetCapacity(Bitmap, 40, 0)
NumPut(40, Bitmap, 0, "uint"), NumPut(cW, Bitmap, 4, "uint")
NumPut(cH, Bitmap, 8, "uint"), NumPut(1, Bitmap, 12, "ushort")
NumPut(32, Bitmap, 14, "ushort"), NumPut(0, Bitmap, 16, "uInt")
Ptr := A_PtrSize ? "UPtr" : "UInt"
PtrA := A_PtrSize ? "UPtr*" : "Uint*"
dc := DllCall("GetDC", Ptr, CtrlhWnd, "Ptr")
hbm := DllCall("CreateDIBSection", Ptr, dc, Ptr, &Bitmap, "uint", 0, PtrA, 0, Ptr, 0, "uint", 0, "Ptr")
hdc := DllCall("CreateCompatibleDC", Ptr, dc)
obm := DllCall("SelectObject", Ptr, hdc, Ptr, hbm)
DllCall("gdiplus\GdipCreateFromHDC", Ptr, hdc, PtrA, G)
DllCall("gdiplus\GdipSetSmoothingMode", Ptr, G, "int", 4)
DllCall("gdiplus\GdipCreateSolidFill", "UInt", Clr, PtrA, pBrush)
DllCall("gdiplus\GdipFillRectangle", Ptr, G, Ptr, pBrush, "float", 0, "float", 0, "float", cW, "float", cH)
DllCall("gdiplus\GdipDeleteBrush", Ptr, pBrush)
DllCall("UpdateLayeredWindow", Ptr, hGdiLayer, Ptr, 0, Ptr, &Rect, "int64*", cW|cH<<32, Ptr, hdc, "int64*", 0, "uint", 0, "UInt*", 0x1FF0000, "uint", 2)
DllCall("SelectObject", Ptr, hdc, Ptr, obm)
DllCall("DeleteObject", Ptr, hbm)
DllCall("DeleteDC", Ptr, hdc), DllCall("DeleteDC", Ptr, dc)
DllCall("gdiplus\GdipDeleteGraphics", Ptr, G)
}
WM_MouseMove(wParam, lParam, msg, hWnd) {
local i, mX, mY
static handle, hwndGui, Higlight, ObjGuiMn, ObjCtrls, FocusRec := 0
ObjGuiMn := {1: "ContextMenu", 2: "Apps"}, pGui1 := {1: "Destroy", 2: "-Disabled"}, pGui2 := {1: "+AlwaysOnTop", 2: "-Disabled"}
ObjCtrls := {1: {1: "hGdiLayer", 2: hGdiLayer}, 2: {1: "hBtnApplistClose", 2: hBtnApplistClose, 3: "0x50E81123"}, 3: {1: "hBttnAddApp", 2: hBttnAddApp, 3: "0x40777777"}, 4: {1: "hBttnExit", 2: hBttnExit, 3: "0x40777777"}, 5: {1: "hBtnOk", 2: hBtnOk, 3: "0x40777777"}, 6: {1: "hBtnClose",  2: hBtnClose, 3: "0x50E81123"}}
For i, v in [hDU, hDuUpFrq, hAppList] {
if (hWnd = v) {
hWndGui := v
}   }
if (hwnd = hMenuDel && !Higlight) {
Higlight := 1
Gui ContextMenu:font,  cffffff
GuiControl, Font, RemApp
}
else if (hWnd = hCntxMn && Higlight = 1) {
Higlight := 0
Gui ContextMenu:font, ce4e4c4
GuiControl, Font, RemApp
}
else if (hwnd = hCntxMn) {
mX := lParam & 0xFFFF, mY := lParam >> 16
i := ((mX < 2 || mX > 170) || (mY < 2 || mY > 22)), i ? (GuiUpdate(ObjGuiMn, pGui1, pGui2))
}
if (!GetKeyState("Lbutton", "D")) {
for i, in ObjCtrls {
if (hwnd = ObjCtrls[i, 2] && FocusRec = 0) {
FocusRec := 1, CtrlID := ObjCtrls[i, 1], CtrlHwnd := ObjCtrls[i, 2], CrtlColor := ObjCtrls[i, 3]
CreateFocusRec(CtrlHwnd, WinExist(), CrtlColor)
}
else if (hwnd = hwndGui && FocusRec = 1) {
FocusRec := 0
GuiUpdate({1: "GdiLayer"}, {1: "Destroy"}), FocusRec := 0
}   }   }   }
Wm_LbuttonDown(wParam, lParam, msg, hWnd) {
if (hwnd = hGdiLayer) {
GuiUpdate("GdiLayer", "Destroy")
MouseGetPos, , , , hWnd, 2
For k, v in Object("hBtnOk", "ButtonOke", "hBtnClose", "DuUpFrqClose", "hBtnApplistClose", "AppListClose"
, "hBttnAddApp", "AddApp", "hBttnExit", "AppListClose", "hMenuDel", "RemApp") {
if (hWnd = %k%) {
gosub % v
}   }
Return
}
For k, v in Object("hDU", "DU_", "hDuUpFrq", "GuiUpFrq_", "hAppList", "Aplst_") {
If (hwnd = %k%) {
FadeInOut(hWnd, "On")
PostMessage, 0xA1, 2, , , % "ahk_id" %k%
FadeInOut(hwnd, "off")
WinGetPos, X, Y, , , % "ahk_id" %k%
vX := v "X", %vX% := X, vY := v "Y", %vY% := Y
IniWrite, % X, % A_ScriptDir "\Settings.ini", Coordinates, % vX
IniWrite, % Y, % A_ScriptDir "\Settings.ini", Coordinates, % vY
}   }   }
FadeInOut(hWnd, Dragg := "", Pcrt = 25) {
SetBatchLines -1
static TransOut, TransparencyOld, Transparency := 0, Handles := {}, HCnt := 0
if (HCnt = 0)
HCnt += 1, Handles := {(HCnt): hwnd}
if (Handles[HCnt] != hwnd)
HCnt += 1, Handles := {(HCnt): hwnd}
if (Dragg = "On") {
WinGet, Transparency, Transparent, ahk_id %hWnd%
TransparencyOld := Transparency
TransOut := (TransparencyOld - (TransparencyOld/100)*Pcrt)
Loop {
If (A_TickCount >= WaitNextTick) {
WaitNextTick := A_TickCount+5
WinSet, Transparent, % Transparency -= 5, ahk_id %hWnd%
If (Transparency <= TransOut)
break
}   }
return
} else if (Dragg = "Off") {
Loop {
If (A_TickCount >= WaitNextTick) {
WaitNextTick := A_TickCount+5
WinSet, Transparent, % Transparency += 5, ahk_id %hWnd%
If (Transparency >= TransparencyOld) {
Transparency := 0
break
}   }   }
return
}
If (Transparency = 0) {
WinGet, Transparency, Transparent, ahk_id %hWnd%
TransparencyOld := Transparency
TransOut := (TransparencyOld - (TransparencyOld/100)*Pcrt)
Loop {
If (A_TickCount >= WaitNextTick) {
WaitNextTick := A_TickCount+25
WinSet, Transparent, % Transparency += 15, ahk_id %hWnd%
If (Transparency >= TransOut){
break
}   }   }
} else {
Loop {
If (A_TickCount >= WaitNextTick) {
WaitNextTick := A_TickCount+25
WinSet, Transparent, % Transparency -= 15, ahk_id %hWnd%
If (Transparency <= TransparencyOld)
break
}   }  }
return
}
ShellMessage(wParam, lParam := 0) {
global
Static CheckLease, NetState := 1, LAN := "192.168"
if (InStr(A_IPAddress1, LAN) && !WindowExist(Applist) && lParam = 0) {
DisableNet()
}
else if (wParam = 1 && WindowExist(Applist) && NetState = 0 || lParam = "StartUp") {
EnableNet(), NetState := 1
if (DuOn = 1 && !Running) {
Running := 1
if (DuMnLbl != "Disable DU Meter") {
Gui, Show, % "x" Du_X "y" Du_Y "NA", DuOsd
menu, DuMeter, rename,  % (DuMnLblNxt := "Enable DU Meter"), % (DuMnLbl := "Disable DU Meter")
Settimer, UpdateDU, % UpdFrq
} else {
Gui, Show, % "x" Du_X "y" Du_Y "NA", DuOsd
Settimer, UpdateDU, % UpdFrq
} }
if (!CheckLease) {
CheckLease := GetWanIp(DNSServer)
if (CheckLease != WanIp) {
Menu, tray, Tip, % (WanIp := CheckLease)
IniWrite, % WanIp, % A_ScriptDir "\Settings.ini", Settings, WanIp
}   }   }
else if (wParam = 2 && !WindowExist(Applist) && NetState) {
DisableNet(), Running := NetState := 0
Gui, hide
Settimer, UpdateDU, Off
}   }
Wm_MouseLeave(wParam, lParam, msg, h) {
hWnd := Format("0x{1:x}", h)
if (hwnd = hLv) {
LV_Modify(RowNr, "-Select")
ControlSend, , {tab}, ahk_id %hWnd%
}   }
TrayNotify(wParam, lParam) {
if (lParam = 0x203 && !WinExist("Applist")) {
Gosub, allowedApps
}
else if (lParam = 0x203 && WinExist("Applist")) {
Gosub, AppListClose
}   }
if (!A_IsAdmin) {
Try {
if (A_IsCompiled) {
Run, *RunAs "%A_ScriptFullPath%"
} else {
Run, *RunAs "%A_AhkPath%" /ErrorStdOut "%A_ScriptFullPath%"
}
} Catch ThisError {
MsgBox % ThisError
}
ExitApp
}
Menu, tray, Icon
Menu, tray, Icon, deskadp.dll, -100
Global IconOpenDu, DuOn,hGdiLayer,IconEnabled,IconNoNetwork,LocalAreaNetwork,WanIp,ipv4,DNSServer,DeviceID,RowNr,RowTxT,MsgID,AutoToggle,ToggleOld,ToggleNew:=ToggleOff,ToggleOff:="Disable AutoToggle",ToggleOn:="Enable AutoToggle",UpdFrq:=1000,IconFile:="pnidui.dll",Applist:=[],Wmi:=ComObjGet("winmgmts:"),DuMnLbl := "Enable DU Meter",DuMnLblNxt := "Disable DU Meter"
UnitIn:="KB",UnitOut:="KB",Download:="0.00",Upload:="0.00",BIn:=BOut:=counter:=0,SldrPos:=1000,SS_CENTERIMAGE:=0x200,Modules:=LoadLibraries("Iphlpapi", "gdiplus"), DU_x := DU_y := Aplst_X := Aplst_Y := "Center"
ReadIni:
Loop, parse, % FileOpen(A_ScriptDir "\Settings.ini", 0).read(), `n, `r
{
if (InStr(A_LoopField, "["))
continue, ReadIni
i := SubStr(A_LoopField, 1, InStr(A_LoopField, "=")-1), %i% := SubStr(A_LoopField, InStr(A_LoopField, "=")+1)
}
Menu, tray, NoStandard
Menu, DuMeter, add, % DuMnLbl, DuMeter
Menu, DuMeter, add, Change Update Interval, GuiUpdateInt
Menu, DuMeter, add, Change Size, DuMeterScale
Menu, DuMeter, add
Menu, DuMeter, add, Double click tray opens DuMeter, TrayOpenDuMeter
Menu, DuMeter, Check, Double click tray opens DuMeter
Menu, DuMeter, UnCheck, Double click tray opens DuMeter
Menu, tray, add, DU Meter, :DuMeter
Menu, tray, add
Menu, tray, add, Configure AppList, allowedApps
Menu, tray, add, % (AutoToggle = 1 || AutoToggle = "") = 1 ? (ToggleNew := ToggleOff, AutoToggle := 1) : (ToggleNew := ToggleOn, AutoToggle = 0), ToggleAutoToggle
GuiControl +g, ToggleAutoToggle()
Menu, tray, add
Menu, tray, add, Network Connections, Connections
Menu, tray, add, Windows Firewall, Firewall
Menu, tray, add, Firewall Advanced, FirewallAdv
Menu, tray, add
Menu, tray, add, Restart script, Restart
Menu, tray, add, Exit, CloseScript
DuGui:
if (!ThisLabel && A_ThisLabel = "DuGui")
ThisLabel := A_ThisLabel
DuSize <= 0 ? (s := "9", h := "28", w1 := "90", w2 := "52", w3 := "20") : (s := "10", h := "34", w1 := "103", w2 := "58", w3 := "25")
Gui, +LastFound +AlwaysOnTop +owner -Caption +Border HwndhDU
Gui, margin, 2, 2
Gui, font, s%s% w600 ce4e4c4 q5
Gui, color, 0x080808
Gui, add, Progress, xm ym h%h% w%w1% hWndhProgress +Background0x1f1f1f +0x8000000
Gui, add, text, xm+1 ym section BackgroundTrans, D:
Gui, add, text, xs BackgroundTrans, U:
Gui, add, text, ys w%w2% BackgroundTrans center section vBytesIn, %Download%
Gui, add, text, xs wp BackgroundTrans center vBytesOut, %Upload%
Gui, add, text, ys w%w3% BackgroundTrans section vUnitIn, %UnitIn%
Gui, add, text, xs wp BackgroundTrans vUnitOut, %UnitOut%
WinSet, Transparent, 180, ahk_id %hDU%
if (ThisLabel = "DuGui") {
ThisLabel := ""
Gui, Show, % "x" DU_x "y" DU_y "NA", DuOsd
Settimer, UpdateDU, % UpdFrq
Return
}
If (!FileExist(A_ScriptDir "\Settings.ini")) {
i := InStr(A_OSVersion, 10), i ? (IconDisabled := 1, IconEnabled := 13, IconNoNetwork := 14) : A_OSVersion = "Win_7" ? (IconDisabled:=26, IconEnabled := 28, IconNoNetwork := 29) : (IconDisabled := 2, IconEnabled:= 15, IconNoNetwork := 16), i:="", List := 1
Gui GetDevices:Default
Gui GetDevices:+LastFound +owner1 +owndialogs +AlwaysOnTop +LabelChooseDev -MinimizeBox -MaximizeBox
Gui GetDevices:add, DropDownList, x12 y12 w345 h125 vList +AltSubmit Choose1
EnumDev := ComObjGet("winmgmts:").ExecQuery("SELECT * FROM Win32_NetworkAdapter where PhysicalAdapter = true")._NewEnum()
while EnumDev[i] {
Name := i.Name, DeviceID := i.DeviceID, DeviceID%A_index% := DeviceID, NetworkCard%A_index% := Name
if (Name) {
GuiControl, , List, %Name%||
}   }
Gui GetDevices:add, Button, x367 y12 w96 h19 gChooseDevOk, Ok
Gui GetDevices:show, , Choose a default network adapter
Return
ChooseDevClose:
ChooseDevEscape:
FileDelete, % A_ScriptDir "\Settings.ini"
ExitApp
ChooseDevOk:
GuiUpdate("GetDevices", "Submit")
GuiControl, +AltSubmit, List
NetworkCard := NetworkCard%List%, DeviceID := DeviceID%List%
IniWrite, %NetworkCard%, % A_ScriptDir "\Settings.ini", Settings, NetworkCard
IniWrite, %DeviceID%, % A_ScriptDir "\Settings.ini", Settings, DeviceID
GuiUpdate({1: "GetDevices", 2: "1"}, {1: "Destroy"}, {1: "Default"})
for i, v in QueryNic() {
IniWrite, % v, % A_ScriptDir "\Settings.ini", Settings, % i
if (i = "ipv4" && InStr(v, "192.168")) {
LocalAreaNetwork := 1
}   }
for i, v in ["LocalAreaNetwork", "IconDisabled", "IconEnabled", "IconNoNetwork"] {
If (v) {
IniWrite, % %v%, % A_ScriptDir "\Settings.ini", Settings, %v%
}   }
If (!FileExist(A_ScriptDir "\NetAccess.acc")) {
for i, v in ["ahk_exe Firefox.exe","ahk_exe Iexplore.exe","ahk_exe Chrome.exe","ahk_exe MicrosoftEdge.exe"] {
FileAppend, %v%`n, %A_ScriptDir%\NetAccess.acc
}   }
List:=i:=v:=EnumDevices:=""
Gosub, RegHookAndMsgs
Return
}
RegHookAndMsgs:
AppList := AHKGroupEX(), DllCall("RegisterShellHookWindow", UInt, A_ScriptHwnd)
MsgID := DllCall("RegisterWindowMessage", Str, "SHELLHOOK")
AutoToggle < 1 ? (ToggleAutoToggle("1")) : ((WindowExist(AppList)) > 0 ? ShellMessage(1, "StartUp") : ShellMessage(2), OnMessage(MsgID,"ShellMessage"))
OnMessage(0x201, "Wm_LbuttonDown"), OnMessage(0x2A3, "Wm_MouseLeave"), OnMessage(0x404, "TrayNotify"), OnMessage(0x200, "Wm_MouseMove")
return
GuiContextMenu:
menu, tray, show, % A_GuiX, % A_GuiY
return
DuMeter:
if (DuMnLbl != "Disable DU Meter") {
Gui, Show, % "x" DU_x "y" DU_y "NA", DuOsd
menu, DuMeter, rename,  % DuMnLbl, % DuMnLblNxt
DuMnLbl := "Disable DU Meter", DuMnLblNxt := "Enable DU Meter", Running := DuOn := 1
Settimer, UpdateDU, % UpdFrq
gosub, UpdateDU
} else {
Settimer, UpdateDU, Off
Gui hide
menu, DuMeter, rename,  % DuMnLbl, % DuMnLblNxt
DuMnLbl := "Enable DU Meter", DuMnLblNxt := "Disable DU Meter", PerfData := Running := DuOn := 0
}
IniWrite, % DuOn, % A_ScriptDir "\Settings.ini", Settings, DuOn
return
DuMeterScale:
IniWrite, % DuSize <= 0 ? (DuSize := 1) : (DuSize := 0), % A_ScriptDir "\Settings.ini", Settings, DuSize
Settimer, UpdateDU, Off
Gui, 1:Destroy
Gosub, DuGui
Return
TrayOpenDuMeter:
Return
UpdateDU:
if (GetKeyState("Lbutton", "D") && WinActive("ahk_id" hDu) || WinActive("ahk_id" hDuUpFrq) || WinActive("ahk_id" hAppList))
return
if (Start && !End) {
DllCall("QueryPerformanceCounter", "Int64*", End)
BytesInOUt := GetNetSpeed(), BInEnd := BytesInOUt[1], BOutEnd := BytesInOUt[2]
If (!CountDownActive)
OldDownload := Download, OldUpload := Upload
mls := ((End-Start)/Frq)/1000, Start := End := 0
KBIn := ((BInEnd-BInStart)/1000)/(mls*0.9765625)
KBOut :=((BOutEnd-BOutStart)/1000)/(mls*0.9765625)
KBIn >= 1024 ? (Download := KBIn/1000 UnitIn := "MB") : (Download := KBIn, UnitIn := "KB")
KBOut >= 1024 ? (Upload := KBOut/1000, UnitOut := "MB") : (Upload := KBOut, UnitOut := "KB")
if (Download >= 1.00) {
if (CountDownActive && Download > 2.00) {
CountDownActive := NextPeriod := ""
}
else if (IdlPeriodOn) {
IdlPeriodOn := NetworkTrafic := 0
Settimer, UpdateDU, % UpdFrq
}
if (!CountDownActive) {
GuiControl(,,,{1: "BytesIn", 2: "BytesOut", 3: "UnitIn", 4: "UnitOut"}, {1: Round(Download, 2)}, {1: Round(Upload, 2)}, {1: UnitIn}, {1: UnitOut})
}   }
else if (Download < 1.00 ) {
if (!IdlPeriodOn) {
CountDownActive := 1
GuiControl(,,,{1: "UnitIn", 2: "UnitOut"}, {1: UnitIn}, {1: UnitOut})
A_TickCount >= NextPeriod ? (IdleTimer := 60000, NextPeriod := A_TickCount+IdleTimer) : (IdleTimer := NextPeriod-A_TickCount, GuiControl(,,,{1: "BytesIn", 2: "BytesOut"}, {1: OldDownload := Round(OldDownload - (Round(OldDownload/2, 2)), 2)}, {1: OldUpload := Round(OldUpload - (Round(OldUpload/2, 2)), 2)}))
If (!NetworkTrafic)
GuiControl(,,,{1: "BytesIn", 2: "BytesOut", 3: "UnitIn", 4: "UnitOut"}, {1: "0.00"}, {1: "0.00"}, {1: UnitIn}, {1: UnitOut}), NetworkTrafic := 1
if ((IdleTimer//1000) <= 1 && CountDownActive) {
GuiControl(,,,{1: "BytesIn", 2: "BytesOut"}, {1: "- - -"}, {1: "- - -"}), IdlPeriodOn := 1, IdleTimer := CountDownActive := 0
SetTimer, UpdateDU, 5000
}   }   }   }
if (!Start) {
DllCall("QueryPerformanceFrequency", "Int64*", Frq), DllCall("QueryPerformanceCounter", "Int64*", Start)
BytesInOUt := GetNetSpeed(), BInStart := BytesInOUt[1], BOutStart := BytesInOUt[2], Frq //= 1000
}
return
GuiUpdateInt:
SldrPos := UpdFrq, TransClr := 0x222222
WinSet, TransColor, %TransClr%, "UpdateInterval"
Gui DuUpFrq:+LastFound +hWndhDuUpFrq +AlwaysOnTop +owner1 -Caption +Border
Gui DuUpFrq:margin, 2, 2
Gui DuUpFrq:font, s8 w700 ce4e4c4 q5, lucon
Gui DuUpFrq:color, 0x262626
Gui DuUpFrq:Add, button, x-1 y-1 w0 h0 +Default vBtn1
Gui DuUpFrq:add, Progress, xm ym w481 h61 vBck hWndhProgress +Background0x141414 +0x8000000
Gui DuUpFrq:Add, Text, x0 y0 w441 h15 vStr +%SS_CENTERIMAGE% +Center +TransColor +BackgroundTrans, % SldrPos " Ms"
Gui DuUpFrq:Add, Text, x+27 y4 w13  h13 Center gDuUpFrqClose hwndhBtnClose +TransColor +0x800200, X
Gui DuUpFrq:Add, Text, x17 y20 w35 h30 vBtnOk gButtonOke hwndhBtnOk -Transparent +TransColor +Center +0x800200, OK
Gui DuUpFrq:add, slider, x60 yp h30 w400 vSldrPos gSldrEvents Range500-3000 Line50 +TickInterval500 +AltSubmit +hwndhSldr +Background +TabStop +E0x8 +0x800000, %UpdFrq%
Gui DuUpFrq:Show, h65 w485, UpdateInterval
WinSet, Transparent, 210, % "ahk_id" hDuUpFrq
Return
SldrEvents:
Gui, submit, nohide
GuiControl, , Str, % SldrPos " Ms"
UpdFrqOld := UpdFrq, SldrPosOld := SldrPos, UpdFrq := SldrPos
UpdFrqOld < UpdFrq ? (SldrMoved := UpdFrq-UpdFrqOld) : (SldrMoved := UpdFrqOld-UpdFrq)
if (A_GuiEvent < 8) {
for i, k in ["LEFT", "RIGHT", "UP", "DOWN", "WHEELUP", "WHEELDOWN", "PGUP", "PGDN", "HOME", "END"] {
while (GetKeyState(k))    {
KeyWait % %k%
ControlFocus, ahk_class msctls_trackbar321
ControlSend, ahk_class msctls_trackbar321, {Tab down}{Tab up}, ahk_id %hDuUpFrq%
ControlFocus, ahk_class Static1
}   }  }
Gui, submit, nohide
return
ButtonOke:
Gui, Submit, NoHide:
IniWrite, %UpdFrq%, % A_ScriptDir "\Settings.ini", Settings, UpdFrq
Gui DuUpFrq:Destroy
Gui 1:-Disabled
If (DuOn = 1) {
Settimer, UpdateDU, %UpdFrq%
gosub, UpdateDU
}
return
DuUpFrqGuiEscape:
DuUpFrqClose:
GuiUpdate({1: "DuUpFrq", 2: "1"}, {1: "Destroy"}, {1: "-Disabled"})
return
allowedApps:
if (WinExist("Applist")) {
Gosub, AppListClose
Return
}
ClipBrdOld := Clipboard, Clipboard := A_IconNumber
Menu, tray, Icon, deskadp.dll, -100
Gui Apps:Default
Gui Apps:+LastFound +AlwaysOnTop +owner1 -Caption +Border hWndhAppList
Gui Apps:color, 0x080808
Gui Apps:font
Gui Apps:font, s9 w600 ce4e4c4 q5, Lucida Console
Gui Apps:add, Picture, xm ym h16 w16 +AltSubmit icon1, deskadp.dll
Gui Apps:add, Text, x+m, Applist
Gui Apps:add, Text, x+153 y5 w13  h13 gAppListClose hWndhBtnApplistClose +0x800200 Center, X
Gui Apps:add, ListView, x13 y40 w240 h190 Section +Background0x202020 gLVSubroutine vAppList hWndhLv -hdr, AppList
For i, App in Applist
LvSize := LV_Add("", SubStr(App, 9)), i := ""
GuiControl +AltSubmit, AppList
Gui Apps:add, Text, xs w115 h20 +Section hWndhBttnAddApp vBttn gAddApp +0x200 +border Center, Add App
Gui Apps:add, Text, ys wp hp hWndhBttnExit gAppListClose +0x200 +border Center, Exit
Gui Apps:Show, x%Aplst_X% y%Aplst_Y% w266 h269, Applist
WinSet, Transparent, 220, % "ahk_id " hAppList
Menu, tray, Icon, % IconFile, % Clipboard
Clipboard := ClipBrdOld, ClipBrdOld := ""
return
LVSubroutine:
Gui, Submit, NoHide
if (A_guiEvent = "RightClick") {
RowNr := A_EventInfo
LV_GetText(RowTxT, A_EventInfo)
s := StrLen(" Delete: " RowTxT)*8.5
if (RowTxT != "" && RowTxT != "AppList") {
CoordMode, Mouse, Screen
Gui Apps:+Disabled
Gui ContextMenu:Default
Gui ContextMenu:+LastFound +AlwaysOnTop +owner1 -Caption HwndhCntxMn
Gui ContextMenu:margin, 1, 1
Gui ContextMenu:font, s9 w600 ce4e4c4 q5, Lucida Console
Gui ContextMenu:color, 0x080808
Gui ContextMenu:add, text, xm+10 ym+2 h20 w%s% +section +0x200 vRemApp gRemApp HwndhMenuDel, % " Delete: " RowTxT
MouseGetPos, mX, mY
Gui ContextMenu:show, % "x" mX-5 "y" mY-5 "w" s+20 "h" 26, ContextMenu
WinSet, Transparent, 230, % "ahk_id " hCntxMn
}   }
LV_Modify(A_EventInfo, "-Select")
ControlSend, , {tab}, ahk_id %hLv%
Gui, Submit, NoHide
return
AddApp:
GuiUpdate("Apps", "hide")
FileSelectFile, App, M3, C:\, ,*.exe
GuiUpdate("Apps", "Default", "Show", "Submit", "+AlwaysOnTop")
Loop, parse, App, `n
{
if (A_Index >= 2) {
AppList := AHKGroupEX(0, A_LoopField)
LV_Add((LvSize+=1), SubStr(AppList[LvSize], 9))
}   }
return
RemApp:
GuiUpdate({1: "GdiLayer", 2: "ContextMenu", 3: "Apps"}, {1: "Destroy"}, {1: "Destroy"}, {1: "-Disabled", 2: "Default", 3: "+AlwaysOnTop"})
LV_Delete(RowNr), Applist := AHKGroupEX(RowNr), LvSize -= 1
if (FileExist("NetAccess.acc"))
FileDelete, NetAccess.acc
For i, App in Applist
FileAppend, %App%`n, %A_ScriptDir%\NetAccess.acc
GuiUpdate("Apps", "Submit")
return
AppsGuiEscape:
AppListClose:
GuiUpdate({1: "Apps", 2: "1"}, {1: "-Disabled", 2: "Default", 3: "Submit", 4: "Destroy"}, {1: "Default"})
return
Connections:
Run % A_WinDir "\explorer.exe shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}\0\::{7007ACC7-3202-11D1-AAD2-00805FC1270E}"
return
Firewall:
Run % A_WinDir "\explorer.exe shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}\0\::{4026492F-2F69-46B8-B9BF-5654FC07E423}"
return
FirewallAdv:
Run % A_WinDir "\system32\wf.msc"
return
Restart:
SetTitleMatchMode, 1
if ((hwnd := WinExist("AutoGUI ")) && A_ThisLabel != "DuMeterScale") {
if (hwnd != WinActive())
WinActivate, ahk_id %hwnd%
Send ^s
}
SkipSave:
if (A_IsCompiled) {
Run *RunAs "%A_ScriptFullPath%" /restart
} else {
Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
}
~Esc & Alt::
Exit:
CloseScript:
FreeLibraries(Modules)
ExitApp
----------------------------------------------------------------- UDATES -----------------------------------------------------------------
ToggleNic V2.0.6
  • Dragging a Gui will fade out that GUI bij 25% of it's original transparency.
  • Resize DU meter code is optimized.
  • Better support for a connection without a home router.
  • If the OS enables network, the script will disable it again if needed.
    A check is performed when each application starts or stops with the conditions that. The ip is not loopback or AIPA
    and a window in the Applist does not exist. The ip is released when these conditions evaluate as true.
  • Added help end explanations within the script.
ToggleNic V2.0.5
  • Replaced COM object for the network speed with DLLCall because I couldn't get the COM refresher to work.
    And it's much faster.
  • Double click the tray icon to open the configure apps gui.
    I will later add a option to choose between the apps or DuMeter gui.
  • Instead of disabling the Nic, now just the ip is released from the DHCP server.
    This is much faster.
  • Removed the toggle device On/Off menu option and replaced it with a feature to toggle
    auto-toggle. Which seems to make more sense and in it's essence does the same thing.
  • DuMeter can be resized to a fixed larger size.
  • I themed the GUI.
  • Fixed some bugs and optimized performance, thus lots of code was rewritten.
ToggleNic V2.0.3
  • Replaced the loop that monitored when a allowed application was launched or closed,
    for a shell message monitor. The monitor checks if each new launched application is in
    the allowed list or not. Thus reducing CPU usage nearly to zero.
ToggleNic V2.0.2
  • Automagically detects if you're behind a router.
  • Code is improved and adapted to a more expressive and modern ahk style.
  • Tray status icons now show when the nic is On, Off or No network connection available.
  • Compatibility added for win8
ToggleNic v2.0.0 Features:
  • Complete rewritten code from version 1.0
  • Turn you're network device on or off, by user specified application(s).
  • Auto toggle can be turned off
  • Active system tray status icons.
  • Tray icon Mouse over shows you're public ip, even when behind a router.
  • Bandwidth or D/U Meter. With tiny transparent draggable window. A slider control to change the update interval.
  • Supports and tested on window10, windows8 and windows7
Attachments
Visuals-4.png
Visuals-4.png (54.51 KiB) Viewed 2046 times
Last edited by megnatar on 08 Jul 2018, 07:57, edited 240 times in total.
Gweek
Posts: 64
Joined: 24 Sep 2015, 06:29

Re: ToggleNic

07 Dec 2015, 15:31

megnatar wrote:Here is a little something I made, you can think of it as some sort of security tool. And with windows10 constantly demands a connection with Microsoft I thought ppl might like it. Why use something when you dont need it, so I switch it off.

Features are:
- Turns you're network device on/off based on application rules from list
- No more ugly big windows10 try menu for the network adapter.
- Tray menu options to turn nic on/off.
- Tray menu option to open the nic settings in control panel.

On first run the script will make a file NetAccess.acc and add Firefox/IE/Opera/Chrome as default apps. And it will also switch off you're internet connection right away.
To add you're apps that are allowed to switch on the device just add them to the list (NetAccess.acc) following its example. I'm not totally sure if it's 100% compatible with other windows versions then win10, since classes might have a different ID.

ToDo:
Filter out virtual nic's like from VM-ware and VBox.
Add compatibility with 2 nics in one machine.
Optimize the allowed apps list so it can be hold more rules (adding to much will cost more and more cpu cycles)
Finding a better way to make the script wait for allowed app to appear instead of looping constantly.
Removing the windows native tray icon.

Code: Select all

if not A_IsAdmin
{
        Run *RunAs "%A_ScriptFullPath%"
        ExitApp
}
#NoEnv  
#Persistent
#SingleInstance off
DetectHiddenWindows, on
SetWorkingDir %A_ScriptDir% 
SetBatchLines, -1
SetWinDelay, -1
ListLines, off

for objItem in ComObjGet("winmgmts:\\.\root\CIMV2").ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE PhysicalAdapter  = True")
{
        if (objItem.PNPDeviceID != "ROOT\NET\0000")
        {
                Interface_ID := objItem.DeviceID
        }
        objWMIServiceDisable := ComObjGet("winmgmts:\\" & strComputer & "\root\CIMV2").ExecMethod("Win32_NetworkAdapter.DeviceID='" Interface_ID "'","Disable")
        Menu, tray, Icon,
        Menu, tray, Icon, %A_WinDir%\system32\pnidui.dll,1
}

IfnotExist, %A_ScriptDir%\NetAccess.acc
{
        FileAppend, ahk_exe firefox.exe, %A_ScriptDir%\NetAccess.acc
        FileAppend, `nahk_exe iexplore.exe, %A_ScriptDir%\NetAccess.acc
        FileAppend, `nahk_exe chrome.exe, %A_ScriptDir%\NetAccess.acc
        FileAppend, `nahk_exe opera.exe, %A_ScriptDir%\NetAccess.acc
}
Settimer, EnableAdapter, 700
Menu, tray, Icon
Menu, Tray, NoStandard
Menu, tray, add, Adaper settings, Settings
Menu, tray, add
Menu, tray, add, Enable this network device, TurnOn
Menu, tray, add, Disable this network device, TurnOff
Menu, tray, add
Menu, tray, add, Exit, CloseScript
return

EnableAdapter:
Loop, read, %A_ScriptDir%\NetAccess.acc
{
        Loop, parse, A_LoopReadLine, %A_Tab%
        {
            GroupAdd, NetAccess, %A_LoopField%
        }
}
IfWinExist, ahk_Group NetAccess
{
        Settimer, EnableAdapter, off
        objWMIServiceEnable := ComObjGet("winmgmts:\\" & strComputer & "\root\CIMV2").ExecMethod("Win32_NetworkAdapter.DeviceID='" Interface_ID "'","Enable")
        Menu, tray, Icon,
        Menu, tray, Icon, %A_WinDir%\system32\pnidui.dll,13
        Settimer, DisableAdapter, 700
}
return

DisableAdapter:
IfWinNotExist, ahk_Group NetAccess
{
        Settimer, DisableAdapter, off
        objWMIServiceDisable := ComObjGet("winmgmts:\\" & strComputer & "\root\CIMV2").ExecMethod("Win32_NetworkAdapter.DeviceID='" Interface_ID "'","Disable")
        Menu, tray, Icon
        Menu, tray, Icon, %A_WinDir%\system32\pnidui.dll,1
        Settimer, EnableAdapter, 700
}
return

TurnOn:
Menu, tray, Icon
Menu, tray, Icon, %A_WinDir%\system32\pnidui.dll,13
objWMIServiceEnable := ComObjGet("winmgmts:\\" & strComputer & "\root\CIMV2").ExecMethod("Win32_NetworkAdapter.DeviceID='" Interface_ID "'","Enable")
return

TurnOff:
Menu, tray, Icon,
Menu, tray, Icon,  %A_WinDir%\system32\pnidui.dll,1
objWMIServiceDisable := ComObjGet("winmgmts:\\" & strComputer & "\root\CIMV2").ExecMethod("Win32_NetworkAdapter.DeviceID='" Interface_ID "'","Disable")
return

Settings:
Run, %A_WinDir%\explorer.exe shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}\3\::{7007ACC7-3202-11D1-AAD2-00805FC1270E}
return

CloseScript:
ExitApp
You are about too read some bad english. and i am really sorry about it i am not a native english speaker

Hey how are U ? Hope U must be fine. :xmas: :)
ahmm okay here i start it. U made a superb skin exactly what i was looking for it have everything for what i need except somethings.Can u plz plz i mean plz make it work with my windows 10 .this script disables the nic just fine but this dosen't enable them when you go to the menu tray icon and click it.
ScreenShot_20151207194420.png
ScreenShot_20151204054705.png
can you plz add one more functionalities

I want this script to enable and disable via F1 keystroke U must be annoyed right now because of these requests sorry and

Last time U made a really awsm script thanxxx ;)

and note : Hope i could make the script like this in the future right now i am just a nobody thanxxx
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: ToggleNic

07 Dec 2015, 22:36

Hey Droyk,

Noted!
Its good you give me a problem, it helps me improve my skills and writing a better script at the same time :D
So yes no problem. But I will take a look and solve you're problem in due time. At the moment I'm kinda busy with updating some other scrip I wrote, and also teaching myself regular expressions.

Nope I don't have a short fuse, not easy to annoy. I rather laugh then get angry :D It's Better for body and mind.
hehe
Gweek
Posts: 64
Joined: 24 Sep 2015, 06:29

Re: ToggleNic

07 Dec 2015, 22:46

megnatar wrote:Hey Droyk,

Noted!
Its good you give me a problem, it helps me improve my skills and writing a better script at the same time :D
So yes no problem. But I will take a look and solve you're problem in due time. At the moment I'm kinda busy with updating some other scrip I wrote, and also teaching myself regular expressions.

Nope I don't have a short fuse, not easy to annoy. I rather laugh then get angry :D It's Better for body and mind.
hehe
Thanxx for an awsm replay.

Nope I don't have a short fuse, not easy to annoy. I rather laugh then get angry :D It's Better for body and mind.
hehe
Thanxx it made my smile :)

and can you plz post your scripts more often i like trying stuffs so maybe i could help you to solve some of the problems(well there is noway i could do that but still if you want any help plz contact :) )
i am glad you are such a nice person :)

And one last thing can you plz tell me how much time it will take to solve the problems(Approx.)thanxx
User avatar
Wickster
Posts: 21
Joined: 19 Apr 2014, 23:02

Re: ToggleNic

02 Jan 2016, 21:43

Just what I was looking for ! Thank you so much !


On another note, is there a way to add a button off/on toggle for it ? or maybe you already have one ?
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: ToggleNic

17 Jun 2016, 08:02

Wickster wrote:Just what I was looking for ! Thank you so much !


On another note, is there a way to add a button off/on toggle for it ? or maybe you already have one ?
Done!
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

17 Jun 2016, 08:28

Update

Changes:
6-17-2016
- Added comments for clarification.
- Optimized code here and there.
Gweek
Posts: 64
Joined: 24 Sep 2015, 06:29

Re: Turn Network device on/off by application

24 Jun 2016, 22:16

Hey megnatar Now it's working fine but can't we disable two network connection or multiple network connections at the same time &
and can't we just enable and disable via a keyboard shortcut forexample press start+shift+e to toggle enable/disable the network connections
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

03 Jul 2016, 11:55

Small update:
Added sleep here and there to give the script some time to finish it's actions.
Fixed: tray icon failed sometimes to load properly.
Correction made to typo's
ToolTip.png
ToolTip.png (10.8 KiB) Viewed 4959 times
Last edited by megnatar on 13 Aug 2016, 11:32, edited 2 times in total.
ozzii
Posts: 327
Joined: 30 Oct 2013, 06:04

Re: Turn Network device on/off by application

04 Jul 2016, 00:28

2 things:
1 - Add something to see if the NIC is ON/OFF
2 - when the gui is closed with the 'X', the script is still running in the background.
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

05 Jul 2016, 13:31

ozzii wrote:2 things:
1 - Add something to see if the NIC is ON/OFF
2 - when the gui is closed with the 'X', the script is still running in the background.
One:
Like I explained in my post.
The device status is shown through the tray icon and the mouse over tool tip.
What is you're OS version?

Two:
It suppose to be running in the background. The gui is a one time show only and is there to select the nic when launched for the first time.
Though, thank you for making me realize that I needed to add GuiClose:
Last edited by megnatar on 13 Aug 2016, 11:20, edited 2 times in total.
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

05 Jul 2016, 14:26

Droyk wrote:Hey megnatar Now it's working fine but can't we disable two network connection or multiple network connections at the same time &
and can't we just enable and disable via a keyboard shortcut for example press start+shift+e to toggle enable/disable the network connections
Sure I could make it in such a way that it can handle multiple nics. But that's beyond the scope of my tool. I did not write it to be used on a server.
How ever, you could just change my script you're self to achieve your goal All you need to do is duplicate what I've already written. All you need is already there.

To create a hotkey, just specify one above the labels TurnOn: and TurnOff:
ozzii
Posts: 327
Joined: 30 Oct 2013, 06:04

Re: Turn Network device on/off by application

06 Jul 2016, 01:36

Well I didn't saw the icon because at the first launch the script is paused.
For me the over icon is always blank. No informations.
Also when I do a "restart script" ; I have this error:
Error: Failed attempt to launch program or document:
---> 328: Run,*RunAs "%A_ScriptFullPath%"
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

07 Jul 2016, 04:28

Oke, I need to check how the script behaves when it's running from a account with basic user rights.
I will get back on this later, as I have little time at the moment.

Thanks for the input!
ozzii
Posts: 327
Joined: 30 Oct 2013, 06:04

Re: Turn Network device on/off by application

08 Jul 2016, 01:35

Well I don't have basic rights because I am Administrator (Win7).
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

08 Jul 2016, 18:07

Indeed, from reading the hotkey manual I now know my problem is the array in function GetIpInfo(). I think its because it lags the .next() method. Because they IPAddress key is actually a array by itself and will hold all the addresses available on the system. .next() method terminates the loop when a object is empty or 0. I did not use .next() so if there is a empty position in IPAddress[] then the value in my variable ipv4 will be deleted again. Running the script trough the debugger confirms this since because variable ipv4 briefly holds a ip and then it's empty again.


I'm not surprised I made some coding errors here and there, since this script is the first one where I've written my own functions and enumerator. So it's kinda new to me.

Anyway.. I'm sure I will fix it soon enough.
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

09 Jul 2016, 19:54

Update:
Fixed function GetNicInfo() it sometimes didn't get the IpAddress because the enumerator tried to get all the 61 objects in Win32_NetworkAdapterConfiguration. Kinda silly when I only need 3 value's, so. I replaced the enum with a for loop, iteration occurs only once getting the value's I need in one go. Also added to the expression "Where index = var" I believe that's more accurate. It should work fine now
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

15 Jul 2016, 13:31

Update:
Improved performance:
Reduced the number of 'IF' evaluations
Reduced sleep period from 100 to 10
Corrections made to some spelling here and there.
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

23 Jul 2016, 14:39

Update:
Added working function for bandwidth monitor. This feature needs further implementation (not fully working yet)
User avatar
megnatar
Posts: 83
Joined: 27 Oct 2014, 20:49
GitHub: Megnatar
Location: The Netherlands

Re: Turn Network device on/off by application

24 Jul 2016, 00:54

Update:
Added bandwidth meter.
Moved the options in tray menu to toggle device manually to submenu "ToggleNic Manually"
DU-Meter.png
ToDo:
Need to convert kB/s to MB/s once bandwidth is greater then 1024 kB/s
Last edited by megnatar on 13 Aug 2016, 13:37, edited 1 time in total.

Return to “Scripts and Functions”

Who is online

Users browsing this forum: D4RQS1D3R, TAC109 and 51 guests