在消息框,计时器内调用一个函数

时间:2016-02-11 15:59:05

标签: powershell timer messagebox

我有一个计时器,我为我的一个脚本设置,我已经设置了所有部分但似乎无法让计时器在框内调用,它将调用powershell然后调出框。我要做的是让它倒计时2分钟然后关闭。以下是我的代码

[void] [System.Reflection.Assembly]::LoadWithPartialName ("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 

$x = 2*60
$length = $x / 100

Function timer () 
{While($x -gt 0) {
$min = [int](([string]($x/60)).split('.')[0])
$text = " " + $min + " minutes " + ($x % 60) + " seconds left"
Write-Progress "Building Account" -status $text -perc ($x/$length)
start-sleep -s 1
$x--
}
}


$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Timer Example"
$objForm.Size = New-Object System.Drawing.Size(330,380) 
$objForm.StartPosition = "CenterScreen"

$lblLog = New-Object System.Windows.Forms.Label
$lblLog.Location = New-Object System.Drawing.Size(10,230) 
$lblLog.Size = New-Object System.Drawing.Size(80,20) 
$lblLog.Text = timer

$objForm.Controls.Add($lblLog) 

$objForm.Add_Shown({$objForm.Activate()})

[void] $objForm.ShowDialog()

1 个答案:

答案 0 :(得分:0)

您当前的代码创建Label对象,然后在将其添加到表单之前循环遍历整个倒计时。 PowerShell是单线程的,这意味着您可以运行代码或响应式表单。如果你想要两者,它会很快变得非常复杂。

乔布斯并不是一个很好的练习,而且我从未在表格中使用过它们,理想情况下你会使用另一个运行空间。

$x = 100

$objForm = New-Object System.Windows.Forms.Form 
$objForm.Text = "Timer Example"
$objForm.Size = New-Object System.Drawing.Size(330,380) 
$objForm.StartPosition = "CenterScreen"

$lblLog = New-Object System.Windows.Forms.Label
$lblLog.Location = New-Object System.Drawing.Size(10,230) 
$lblLog.Size = New-Object System.Drawing.Size(80,20)
$lblLog.Text = "Testing"
$objForm.Controls.Add($lblLog)

[PowerShell]$command = [PowerShell]::Create().AddScript({
    Param
    (
        [System.Windows.Forms.Label]$label,
        $x
    )
    While($x -gt 0) {
        $min = [int](([string]($x/60)).split('.')[0])
        $text = " " + $min + " minutes " + ($x % 60) + " seconds left"
        $label.BeginInvoke([System.Action[string]]{
            Param($text)

            $label.Text = $text
        }, $text)
        start-sleep -s 1
        $x--
    }
})
$command.AddParameters(@($lblLog, $x)) | Out-Null

$command.BeginInvoke() | Out-Null
$objForm.ShowDialog()

这样做是创建另一个运行空间,PowerShell可以与主控制台并行运行,并将计时器放在那里。然而,表单也是单线程,因此我们需要调用更新Label的操作(有点像说"嘿,你可以在你自由时执行此操作吗?")。我们使用BeginInvoke只是告诉它更新但不等待,因为您正在运行计时器并且必须等待表单可用才会丢弃您的计数器。

此测试对我来说没问题,但表格和标签需要调整大小以适合您的目的。