关闭后再次打开相同的表格

Open the same Form again after Closing

要么是我太笨没法google正确解决,要么是问题太明显无法解决。

我正在使用第二个小窗体在 运行 函数时显示进度条(加载一些信息需要一些时间,这会增加一些不错的响应速度)

函数完成并检索数据后,进度条窗体关闭 $formbar.Close()

如果我在同一个实例中再次调用该函数,进度条将不会再次显示,因为它已经被处理掉了。我该如何改变它?我不想“隐藏”进度条。

$formbar = New-Object System.Windows.Forms.Form
$progressBar1 = New-Object System.Windows.Forms.ProgressBar

$formbar.ControlBox = $false
$formbar.Size = '265,45'
$formbar.StartPosition = "CenterScreen"
$progressBar1.Style = "Continuous"
$progressBar1.ForeColor = "#009374"
$ProgressRange = 1..100
$ProgressMinMax = $ProgressRange | Measure -Minimum -Maximum

$progressBar1.Location = '0,0'
$progressBar1.Size = '250,30'
$progressBar1.Visible = $True
$progressBar1.Minimum = $ProgressMinMax.Minimum
$progressBar1.Maximum = $ProgressMinMax.Maximum
$progressBar1.Step = 10
$formbar.Controls.Add($progressBar1)
$formbar.Show()

有什么想法吗?

您每次都需要重新创建整个表单:

function New-ProgressBarForm {
  $null = . {
    $formbar = New-Object System.Windows.Forms.Form
    $progressBar1 = New-Object System.Windows.Forms.ProgressBar

    $formbar.ControlBox = $false
    $formbar.Size = '265,45'
    $formbar.StartPosition = "CenterScreen"
    $progressBar1.Style = "Continuous"
    $progressBar1.ForeColor = "#009374"
    $ProgressRange = 1..100
    $ProgressMinMax = $ProgressRange | Measure -Minimum -Maximum

    $progressBar1.Location = '0,0'
    $progressBar1.Size = '250,30'
    $progressBar1.Visible = $True
    $progressBar1.Minimum = $ProgressMinMax.Minimum
    $progressBar1.Maximum = $ProgressMinMax.Maximum
    $progressBar1.Step = 10
    $formbar.Controls.Add($progressBar1)
  }

  return [pscustomobject]@{
    Form = $formbar
    ProgressBar = $progressBar1
  }
}

然后调用:

$progress = New-ProgressBarForm
$progress.Form.Show()

想显示的时候

Mathias 回答了问题,但你也问了为什么,所以这就是原因。

当用户关闭您的表单时,通过使用 X 或关闭按钮关闭表单,或者当 Form.Close() 方法关闭时,the following takes place:

When a form is closed, all resources created within the object are closed and the form is disposed. You can prevent the closing of a form at run time by handling the Closing event and setting the Cancel property of the CancelEventArgs passed as a parameter to your event handler. If the form you are closing is the startup form of your application, your application ends.

我们可以通过查看对象的 IsDisposed 属性.

来判断它的句柄是否仍然可用
#before showing
PS> $formBar.IsDisposed
False

PS> $formBar.Show()

PS> $formBar.IsDisposed
True

TLDR:与内存管理有关。一个表格一旦出现又关闭,它就从记忆中消失了,但它所触及的变量将永远留在我们的心中。