2016-02-11 24 views
1

我有一個計時器,我爲我的一個腳本設置了一個計時器,我已經完成了所有的設置,但似乎無法在計時器內調用計時器,它會調用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() 

回答

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,它只是告訴它更新,但不會等待,因爲你正在運行一個計時器,並且不得不等待表單可用纔會拋出計數器。

這個測試對我來說確定,但表單和標籤需要調整大小以適應您的目的。

+0

哦,只是一個說明,大多數流(如輸出和錯誤)不會從單獨的運行空間重定向到主控制檯(儘管由於某種原因警告是??) - 我不知道進展,但我didn我的測試沒有任何結果。 –

+0

$ length無論如何都不會傳遞,所以可能值得編輯它(它確實進入了Streams屬性)。最後,這確實會引發一些錯誤(也包含到Streams中),因爲$ command在表單顯示之前開始運行,這意味着它會嘗試在標籤可用之前更新一次或兩次標籤。你可以投入兩秒鐘的等待時間,或者使用try/catch,甚至忽略它,仍然可以運行。 –

相關問題