关闭由启动作业任务控制的Powershell表单

时间:2012-02-24 08:08:07

标签: user-interface powershell start-job

我的任务是使用GUI构建一个PowerShell脚本,使用户能够安装网络打印机。我已经成功地设法这样做了,但是我无法满足用户在打印机安装时显示“请等待”窗口的要求。如果我从主线程切换到窗口,GUI挂起。如果我将窗口显示为单独的工作,我永远无法再次关闭窗口。这是我的尝试:

$waitForm = New-Object 'System.Windows.Forms.Form'

$CloseButton_Click={

    # open "please wait form"
    Start-Job -Name waitJob -ScriptBlock $callWork -ArgumentList $waitForm

    #perform long-running (duration unknown) task of adding several network printers here
    $max = 5
    foreach ($i in $(1..$max)){
        sleep 1 # lock up the thread for a second at a time
    }

    # close the wait form - doesn't work. neither does remove-job
    $waitForm.Close()
    Remove-Job -Name waitJob -Force
}

$callWork ={

    param $waitForm

    [void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
    $waitForm = New-Object 'System.Windows.Forms.Form'

    $labelInstallingPrintersPl = New-Object 'System.Windows.Forms.Label'
    $waitForm.Controls.Add($labelInstallingPrintersPl)
    $waitForm.ClientSize = '502, 103'
    $labelInstallingPrintersPl.Location = '25, 28'
    $labelInstallingPrintersPl.Text = "Installing printers - please wait..."

    $waitForm.ShowDialog($this)
} 

有没有人知道在长时间运行的任务结束后如何解除$ waitForm窗口?

3 个答案:

答案 0 :(得分:2)

您可以尝试在主线程上运行Windows窗体对话框并在后台作业中执行实际工作:

Add-Type -Assembly System.Windows.Forms

$waitForm = New-Object 'System.Windows.Forms.Form'
$labelInstallingPrintersPl = New-Object 'System.Windows.Forms.Label'
$waitForm.Controls.Add($labelInstallingPrintersPl)
$waitForm.ClientSize = '502, 103'
$labelInstallingPrintersPl.Location = '25, 28'
$labelInstallingPrintersPl.Text = "Installing printers - please wait..."
$waitForm.ShowDialog($this)

Start-Job -ScriptBlock $addPrinters | Wait-Job

$waitForm.Close()

$addPrinters = {
    $max = 5
    foreach ($i in $(1..$max)) {
        sleep 1 # lock up the thread for a second at a time
    }
}

答案 1 :(得分:2)

第一个答案是正确的,在主线程上创建表单并在单独的线程上执行长时间运行的任务。之所以在表单被解除之后才执行主代码是因为你正在使用表单的'ShowDialog'方法,这种方法会导致后续的代码执行,直到表单被关闭。

相反使用'show'方法,代码执行将继续,你应该包括一些事件处理程序来处理表单

Add-Type -Assembly System.Windows.Forms

$waitForm = New-Object 'System.Windows.Forms.Form'
$labelInstallingPrintersPl = New-Object 'System.Windows.Forms.Label'
$waitForm.Controls.Add($labelInstallingPrintersPl)
$waitForm.ClientSize = '502, 103'
$labelInstallingPrintersPl.Location = '25, 28'
$labelInstallingPrintersPl.Text = "Installing printers - please wait..."

$waitForm.Add_FormClosed({
$labelInstallingPrintersPl.Dispose()
$waitForm.Dispose()
})

$waitForm.Show($this)

Start-Job -ScriptBlock $addPrinters | Wait-Job

$waitForm.Close()

$addPrinters = {
    $max = 5
    foreach ($i in $(1..$max)) {
        sleep 1 # lock up the thread for a second at a time
    }
}

答案 2 :(得分:0)

如何在主GUI窗口中添加Windows.Forms.Progressbar?在添加打印机时,请逐步更新其值,以便用户看到应用程序正在运行。