Jump to content
Sign in to follow this  
guinness

_InetGetGUI() and _InetGetProgress()

Recommended Posts

guinness

This is just a 2014 update of  >_InetGetGUI() and >_InetGetProgress(). I have purposely left the original examples untouched just for nostalgic purposes.

 

_InetGetGUI() Example and Function:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7

#include <GUIConstantsEx.au3>
#include <InetConstants.au3>
#include <MsgBoxConstants.au3>
#include <StringConstants.au3>

Example()

Func Example()
    Local $hGUI = GUICreate('_InetGetGUI()', 370, 90)
    Local $iLabel = GUICtrlCreateLabel('Welcome to the simple downloader', 5, 5, 270, 40)
    Local $iStartClose = GUICtrlCreateButton('&Download', 275, 2.5, 90, 25)
    Local $iProgressBar = GUICtrlCreateProgress(5, 60, 360, 20)
    GUISetState(@SW_SHOW, $hGUI)

    Local $sFilePath = '', $sFilePathURL = 'http://ipv4.download.thinkbroadband.com/5MB.zip'
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $iStartClose
                $sFilePath = _InetGetGUI($sFilePathURL, $iLabel, $iProgressBar, $iStartClose, @TempDir)
                Switch @error ; Check what the actual error was.
                    Case 1 ; $INETGET_ERROR_1
                        MsgBox($MB_SYSTEMMODAL, 'Error', 'Check the URL or your Internet connection is working.')

                    Case 2 ; $INETGET_ERROR_2
                        MsgBox($MB_SYSTEMMODAL, 'Fail', 'It appears the user interrupted the download.')

                    Case Else
                        MsgBox($MB_SYSTEMMODAL, 'Success', 'Successfully downloaded "' & $sFilePath & '"')

                EndSwitch

        EndSwitch
    WEnd

    GUIDelete($hGUI)
EndFunc   ;==>Example

; #FUNCTION# ====================================================================================================================
; Name ..........: _InetGetGUI
; Description ...: Download a file updating a GUICtrlCreateProgress()
; Syntax ........: _InetGetGUI($sURL, $iLabel, $iProgress, $iButton[, $sDirectory = @ScriptDir])
; Parameters ....: $sURL                - A valid URL that contains the filename too
;                  $iLabel              - ControlID of a GUICtrlCreateLabel comtrol.
;                  $iProgress           - ControlID of a GUICtrlCreateProgress control.
;                  $iButton             - ControlID of a GUICtrlCreateButton control.
;                  $sDirectory          - [optional] Directory of where to download. Default is @ScriptDir.
; Return values .: Success - Downloaded filepath.
;                  Failure - Blank string & sets @error to non-zero
; Author ........: guinness
; Example .......: Yes
; ===============================================================================================================================
Func _InetGetGUI($sURL, $iLabel, $iProgress, $iButton, $sDirectory = @ScriptDir)
    Local Enum $INETGET_ERROR_0, $INETGET_ERROR_1, $INETGET_ERROR_2
    Local $sFilePath = StringRegExpReplace($sURL, '^.*/', '')
    If StringStripWS($sFilePath, $STR_STRIPALL) == '' Then
        Return SetError($INETGET_ERROR_1, 0, $sFilePath)
    EndIf

    $sFilePath = StringRegExpReplace($sDirectory, '[\\/]+$', '') & '\' & $sFilePath
    Local $iFileSize = InetGetSize($sURL, $INET_FORCERELOAD)
    Local $hDownload = InetGet($sURL, $sFilePath, $INET_LOCALCACHE, $INET_DOWNLOADBACKGROUND)

    Local Const $iRound = 0
    Local $iBytesRead = 0, $iPercentage = 0, $iSpeed = 0, _
            $sProgressText = '', $sSpeed = 'Current speed: ' & _ByteSuffix($iBytesRead - $iSpeed) & '/s'
    Local $hTimer = TimerInit()

    Local $iError = $INETGET_ERROR_0, _
            $sRead = GUICtrlRead($iButton)

    GUICtrlSetData($iButton, '&Cancel')
    While Not InetGetInfo($hDownload, $INET_DOWNLOADCOMPLETE)
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE, $iButton
                GUICtrlSetData($iLabel, 'Download cancelled.')
                $iError = $INETGET_ERROR_2
                ExitLoop
        EndSwitch

        $iBytesRead = InetGetInfo($hDownload, $INET_DOWNLOADREAD)
        $iPercentage = $iBytesRead * 100 / $iFileSize
        $sProgressText = 'Downloading ' & _ByteSuffix($iBytesRead, $iRound) & ' of ' & _ByteSuffix($iFileSize, $iRound) & @CRLF & $sSpeed

        GUICtrlSetData($iLabel, $sProgressText)
        GUICtrlSetData($iProgress, $iPercentage)

        If TimerDiff($hTimer) >= 1000 Then
            $sSpeed = 'Current speed: ' & _ByteSuffix($iBytesRead - $iSpeed) & '/s'
            $iSpeed = $iBytesRead
            $hTimer = TimerInit()
        EndIf
        Sleep(20)
    WEnd

    InetClose($hDownload)
    GUICtrlSetData($iButton, $sRead)

    If $iError > $INETGET_ERROR_0 Then
        FileDelete($sFilePath)
        $sFilePath = ''
    EndIf
    Return SetError($iError, 0, $sFilePath)
EndFunc   ;==>_InetGetGUI

Func _ByteSuffix($iBytes, $iRound = 2) ; By Spiff59
    Local Const $aArray[9] = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']
    Local $iIndex = 0
    While $iBytes > 1023
        $iIndex += 1
        $iBytes /= 1024
    WEnd
    Return Round($iBytes, $iRound) & $aArray[$iIndex]
EndFunc   ;==>_ByteSuffix
 

_InetGetProgress() Example and Function:

#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7

#include <InetConstants.au3>
#include <MsgBoxConstants.au3>
#include <StringConstants.au3>

Example()

Func Example()
    Local $sFilePathURL = 'http://ipv4.download.thinkbroadband.com/5MB.zip'
    Local $sFilePath = _InetGetProgress($sFilePathURL, @TempDir)
    If @error Then
        MsgBox($MB_SYSTEMMODAL, 'Error', 'Check the URL or your Internet connection is working.')
    Else
        MsgBox($MB_SYSTEMMODAL, 'Success', 'Successfully downloaded "' & $sFilePath & '"')
    EndIf
EndFunc   ;==>Example

; #FUNCTION# ====================================================================================================================
; Name ..........: _InetGetProgress
; Description ...: Download a file showing a progress bar using ProgressOn.
; Syntax ........: _InetGetProgress($sURL[, $sDirectory = @ScriptDir])
; Parameters ....: $sURL                - A valid URL that contains the filename too.
;                  $sDirectory          - [optional] Directory of where to download. Default is @ScriptDir.
; Return values .: Success - Downloaded filepath.
;                  Failure - Blank string & sets @error to non-zero
; Author ........: guinness
; Example .......: Yes
; ===============================================================================================================================
Func _InetGetProgress($sURL, $sDirectory = @ScriptDir)
    Local Const $INETGET_ERROR_1 = 1
    Local $sFilePath = StringRegExpReplace($sURL, '^.*/', '')
    If StringStripWS($sFilePath, $STR_STRIPALL) == '' Then
        Return SetError($INETGET_ERROR_1, 0, $sFilePath)
    EndIf

    $sFilePath = StringRegExpReplace($sDirectory, '[\\/]+$', '') & '\' & $sFilePath
    Local $iFileSize = InetGetSize($sURL, $INET_FORCERELOAD)
    Local $hDownload = InetGet($sURL, $sFilePath, $INET_LOCALCACHE, $INET_DOWNLOADBACKGROUND)

    Local Const $iRound = 0
    Local $iBytesRead = 0, $iPercentage = 0, $iSpeed = 0, _
            $sProgressText = '', $sSpeed = 'Current speed: ' & _ByteSuffix($iBytesRead - $iSpeed) & '/s'
    Local $hTimer = TimerInit()

    ProgressOn('', '')

    While Not InetGetInfo($hDownload, $INET_DOWNLOADCOMPLETE)
        $iBytesRead = InetGetInfo($hDownload, $INET_DOWNLOADREAD)
        $iPercentage = $iBytesRead * 100 / $iFileSize
        $sProgressText = 'Downloading ' & _ByteSuffix($iBytesRead, $iRound) & ' of ' & _ByteSuffix($iFileSize, $iRound) & @CRLF & $sSpeed

        ProgressSet(Round($iPercentage, $iRound), $sProgressText, 'Downloading: ' & $sFilePath)

        If TimerDiff($hTimer) >= 1000 Then
            $sSpeed = 'Current speed: ' & _ByteSuffix($iBytesRead - $iSpeed) & '/s'
            $iSpeed = $iBytesRead
            $hTimer = TimerInit()
        EndIf
        Sleep(20)
    WEnd

    InetClose($hDownload)
    ProgressOff()
    Return $sFilePath
EndFunc   ;==>_InetGetProgress

Func _ByteSuffix($iBytes, $iRound = 2) ; By Spiff59
    Local Const $aArray[9] = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB']
    Local $iIndex = 0
    While $iBytes > 1023
        $iIndex += 1
        $iBytes /= 1024
    WEnd
    Return Round($iBytes, $iRound) & $aArray[$iIndex]
EndFunc   ;==>_ByteSuffix
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

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  

  • Similar Content

    • Tersion
      By Tersion
      Why I can't get more than two simultaneously background downloads?
      Simultaneously background downloads with InetGet() works! It was just server limitation from which I downloaded files.
    • rm4453
      By rm4453
      Hello,
       
      I am currently writing a program that parses a massive table from a website, and need a way to add a progress bar while parsing.
      I am currently using the function _IETableWriteToArray($oObj, True) to parse the array. I need the progress bar to update as the table is parsed, not just at the end of the parsing.
      Any help at all would be very much appreciated!
       
      *EDIT --> The array I am left with after parsing is $array[0-50000][16]
    • VollachR
      By VollachR
      Hi,
      I'd like to show a progress bar for an operation performed by an external program my script is running silently, I want to show it in a GUI I created using the GUICtrlCreateProgress but I have no idea how to do it.
      The important thing to point out is that there's no way of knowing how long the external program will run, as it is a file splitter and it depends on the size of file it splits and the split parts size.
      Can someone point me in the right direction or give me an example how to do so?
      This is my RunWait command:
      RunWait($MYFILES1 & '\fsplit.exe -split ' & $Size & ' mb ' & $File & " -f " & $File & "." & $extension) It uses multiple variables declared and set earlier in the script, how will I got about having the progress of that command shown using GUICtrlCreateProgress ? Is it possible?
      Thank you.
    • BrewManNH
      By BrewManNH
      I have created a UDF that will allow you to easily create a customizable GUI with either a standard progress bar or a marquee style progress bar. You can change the size and back ground color of the GUI, as well as the font, font size, and color of the text. The function doesn't require any parameters to operate, but the default text is very generic so you probably would want to set that at the very least.
    • leb
      By leb
      Hello there,
      I am using the function InetGet example in the help files on a website and getting the error 13. First, I searched the help files and the forum for a list of errors to consult to no avail. I suspect this is a 400's server reply based error but it would be nice to get more info about it.
      Please help, thanks.
      L
×