Sunday, December 7, 2008

AHK - UrlDownloadToFile Interruption

This first script is an example of how to pause UrlDownloadToFile, or simply to execute other functions while still downloading. The second is an example of how to pause the download, then exit the script and delete the download file without finishing it. Differences in the second code are highlighted in red.

Size = 300 ; approximate size in bytes of final file

SetTimer, CheckStatus, 10
;Download File
URLDownloadToFile, http://www.autohotkey.com/download/AutoHotkey104706_Install.exe, _tmp_AutoHotkey104706_Install.exe
Return

;Check Status
CheckStatus:
FileGetSize, FSize, _tmp_AutoHotkey104706_Install.exe
If (FSize >= Size) {
Critical ; Make so this thread can't interrupted
SetTimer, CheckStatus, off ; Stop checking status
FileRead, FileData, _tmp_AutoHotkey104706_Install.exe ; Read file
MsgBox % "Done!`n" (ErrorLevel ? "Error: " ErrorLevel : "`n" FileData) ; Done!
; Demonstrates interruption of UrlDownloadToFile
; Size of file stays the same
Loop, 1000 {
FileGetSize, FSize, _tmp_AutoHotkey104706_Install.exe
ToolTip, File Size (Paused): %FSize%
Sleep, 10
}
; Resume Download
SetTimer, CheckStatus2, 10
}
Return

CheckStatus2:
FileGetSize, FSize, _tmp_AutoHotkey104706_Install.exe
ToolTip, File Size (Resumed): %FSize%
Return

~Esc::
SetTimer, ExitApp, 10
Return

ExitApp:
ExitApp

Size = 300 ; approximate size in bytes of final file
OnExit, OnExit ; Execute "OnExit" label when exiting

SetTimer, CheckStatus, 10
;Download File
URLDownloadToFile, http://www.autohotkey.com/download/AutoHotkey104706_Install.exe, _tmp_AutoHotkey104706_Install.exe
Return

;Check Status
CheckStatus:
FileGetSize, FSize, _tmp_AutoHotkey104706_Install.exe
If (FSize >= Size) {
Critical
SetTimer, CheckStatus, off
FileRead, FileData, _tmp_AutoHotkey104706_Install.exe
ToolTip, File Size: %FSize%
MsgBox % "Done!`n" (ErrorLevel ? "Error: " ErrorLevel : "`n" FileData)
FileDelete, _tmp_AutoHotkey104706_Install.exe
; Demonstrates interruption of UrlDownloadToFile
; Size of file stays the same
Loop, 250 {
FileGetSize, FSize, _tmp_AutoHotkey104706_Install.exe
ToolTip, File Size (Paused): %FSize%
Sleep, 10
}
; Exit
ExitApp

}
Return

~Esc::
SetTimer, OnExit, 10
Return

OnExit:
; Create a batch file that will delete the download file and itself
FileAppend, ping http://www.google.com`nDel "%A_ScriptDir%\_tmp_AutoHotkey104706_Install.exe"`n Del "del.bat", del.bat
; Wait for file to exist
Loop {
If (FileExist("del.bat"))
break
}
; Run file
Run, del.bat, %A_ScriptDir%, HIDE
ExitApp


Forum Post

No comments: