当按下“关闭”按钮时,我正在努力打破while
循环。
相反,在开始移动过程之后,我陷入了无尽的循环。
$objForm.Controls.Add($StartButton)
$objForm.Controls.Add($OffButton)
$OffButton = New-Object System.Windows.Forms.Button
$OffButton.Location = New-Object System.Drawing.Size(340,105)
$OffButton.Size = New-Object System.Drawing.Size(90,28)
$OffButton.Text = 'Off'
$OffButton.Name = 'Off'
$OffButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
$OffButton.Add_Click({$script:AktiveLoop = $False})
$objForm.Controls.Add($OffButton)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Size(340,135)
$StartButton.Size = New-Object System.Drawing.Size(90,28)
$StartButton.Text = 'Start'
$StartButton.Name = 'Start'
$StartButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
$StartButton.Add_Click({
$script:AktiveLoop = $true
while ($script:AktiveLoop -eq $true) {
Move-Item $source -Destination $destination
Start-Sleep -Seconds 1.0
if ($script:AktiveLoop = $False) {
break
}
}
})
[void] $objForm.ShowDialog()
答案 0 :(得分:0)
尽管有关于使用DoEvents的讨论,但是似乎并未触发“关闭”按钮这一事实与您放入循环中的Start-Sleep
有关。
Start-Sleep
使表单无响应。如果您使用[System.Windows.Forms.Application]::DoEvents()
,则将处理按钮单击事件。
从用户的角度来看,最好是在首次绘制表单时禁用“关闭”按钮,并在te Click
事件中切换两个按钮的启用状态。
为此,我对示例中给出的代码进行了一些更改:
Add-Type -AssemblyName System.Windows.Forms
$objForm = New-Object System.Windows.Forms.Form
$OffButton = New-Object System.Windows.Forms.Button
$OffButton.Location = New-Object System.Drawing.Size(340,105)
$OffButton.Size = New-Object System.Drawing.Size(90,28)
$OffButton.Text = 'Off'
$OffButton.Name = 'Off'
$OffButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
# initially disable the 'Off' button
$OffButton.Enabled = $false
$OffButton.Add_Click({
$script:AktiveLoop = $false
$OffButton.Enabled = $false
$StartButton.Enabled = $true
})
$objForm.Controls.Add($OffButton)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Size(340,135)
$StartButton.Size = New-Object System.Drawing.Size(90,28)
$StartButton.Text = 'Start'
$StartButton.Name = 'Start'
$StartButton.Font = [System.Drawing.Font]::New("Microsoft Sans Serif", 11)
# initially enable the 'Off' button
$StartButton.Enabled = $true
$StartButton.Add_Click({
# switch the buttons Enabled status so the user can not click the same button twice
$OffButton.Enabled = $true
$StartButton.Enabled = $false
$script:AktiveLoop = $true
while ($script:AktiveLoop) {
# perform some action here. (added -WhatIf here for testing)
Move-Item $source -Destination $destination -WhatIf
# Start-Sleep makes the form unresponsive, so don't use that.
# DoEvents() suspends the current thread and processes
# window messages like a click on the 'Off' button.
[System.Windows.Forms.Application]::DoEvents()
}
})
$objForm.Controls.Add($StartButton)
[void] $objForm.ShowDialog()
$objForm.Dispose()
p.s。您甚至在定义按钮之前就将按钮添加到了表单,所以我删除了它。
希望这会有所帮助