Skip to content

Instantly share code, notes, and snippets.

@santisq
Created November 6, 2023 20:38
Show Gist options
  • Save santisq/c8faf9599ddf1e665e4d5495cc179695 to your computer and use it in GitHub Desktop.
Save santisq/c8faf9599ddf1e665e4d5495cc179695 to your computer and use it in GitHub Desktop.
winform with `.DownloadFileAsync` and progress bar
Add-Type -Assembly System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = [System.Windows.Forms.Form]@{
Size = '500, 150'
FormBorderStyle = 'Fixed3d'
}
$btn = [System.Windows.Forms.Button]@{
Name = 'MyButton'
Text = 'Click Me!'
Size = '90, 30'
Location = '370, 70'
Anchor = 'Bottom, Right'
}
$btn.Add_Click({
$this.Enabled = $false
$downloader.DownloadFileAsync('https://www.7-zip.org/a/7z2301-x64.exe', "$pwd\7Zip.exe")
})
$progress = [System.Windows.Forms.ProgressBar]@{
Name = 'MyProgressBar'
Size = '460, 40'
Location = '10, 10'
}
$form.Controls.AddRange(($btn, $progress))
$downloader = [System.Net.WebClient]::new()
$rs = [runspacefactory]::CreateRunspace($Host)
$rs.Open()
$rs.SessionStateProxy.PSVariable.Set([psvariable]::new('form', $form))
$ps = [powershell]::Create().AddScript({
$registerObjectEventSplat = @{
InputObject = $args[0]
EventName = 'DownloadProgressChanged'
SourceIdentifier = 'WebMainDownloadProgressChanged'
Action = {
[System.Threading.Monitor]::Enter($form)
$progress = $form.Controls.Find('MyProgressBar', $false)[0]
$eventArgs.ProgressPercentage | Out-Host
$progress.Value = $eventArgs.ProgressPercentage
[System.Threading.Monitor]::Exit($form)
}
}
Register-ObjectEvent @registerObjectEventSplat
$registerObjectEventSplat['EventName'] = 'DownloadFileCompleted'
$registerObjectEventSplat['SourceIdentifier'] = 'WebMainDownloadFileCompleted'
$registerObjectEventSplat['Action'] = {
[System.Threading.Monitor]::Enter($form)
$form.Controls.Find('MyButton', $false)[0].Enabled = $true
Write-Host 'Download Completed!'
[System.Threading.Monitor]::Exit($form)
}
Register-ObjectEvent @registerObjectEventSplat
}).AddArgument($downloader)
$ps.Runspace = $rs
$task = $ps.BeginInvoke()
$form.ShowDialog()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment