powershellsubform

powershell reopening subform


I am writing my first subform in PowerShell. When I write my code through everything fires off perfectly. When I close the subform by the x in the window and then reopen it I receive the error:

Exception setting "visible": "Cannot access a disposed object. Object name: 'Form'." At line:5 char:5 $ExampleForm.visible = $true ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting

My Code is below:


function TestFunction
{
    $ExampleForm.enabled = $true
    $ExampleForm.visible = $true
}

$Form = New-Object system.Windows.Forms.Form 
$Form.Size = New-Object System.Drawing.Size(1050,425) 
$form.MaximizeBox = $false 
$Form.StartPosition = "CenterScreen" 
$Form.FormBorderStyle = 'Fixed3D' 
$Form.Text = "Test Form"  

$ExampleForm = New-Object system.Windows.Forms.Form 
$ExampleForm.Size = New-Object System.Drawing.Size(550,425) 
$ExampleForm.MaximizeBox = $false 
$ExampleForm.StartPosition = "CenterScreen" 
$ExampleForm.FormBorderStyle = 'Fixed3D'
$ExampleForm.Text = "Example"
$ExampleForm.Visible = $False

$TestButton = new-object System.Windows.Forms.Button
$TestButton.Location = new-object system.drawing.size(401,140) 
$TestButton.Size = new-object system.drawing.size(80,50)
$TestButton.Text = "Test"
$TestButton.Add_Click({TestFunction}) 
$TestButton.TabIndex = 33
$Form.Controls.Add($TestButton)

$Form.ShowDialog()

What am I doing wrong???


Solution

  • You'll want to create a new form every time:

    function TestFunction
    {
      $ExampleForm = New-Object System.Windows.Forms.Form 
      $ExampleForm.Size = New-Object System.Drawing.Size(550,425) 
      $ExampleForm.MaximizeBox = $false 
      $ExampleForm.StartPosition = "CenterScreen" 
      $ExampleForm.FormBorderStyle = 'Fixed3D'
      $ExampleForm.Text = "Example"
    
      # ShowDialog will prevent re-focusing on parent form until this one closes
      [void]$ExampleForm.ShowDialog()
    
      # If you don't want this modal behavior, use `Show()` instead:
      # [void]$ExampleForm.Show()
    }
    
    $Form = New-Object System.Windows.Forms.Form 
    $Form.Size = New-Object System.Drawing.Size(1050,425) 
    $Form.MaximizeBox = $false 
    $Form.StartPosition = "CenterScreen" 
    $Form.FormBorderStyle = 'Fixed3D' 
    $Form.Text = "Test Form"  
    
    $TestButton = New-Object System.Windows.Forms.Button
    $TestButton.Location = New-Object System.Drawing.Size(401,140) 
    $TestButton.Size = New-Object System.Drawing.Size(80,50)
    $TestButton.Text = "Test"
    $TestButton.add_Click({TestFunction}) 
    $TestButton.TabIndex = 33
    $Form.Controls.Add($TestButton)
    
    $Form.ShowDialog()