How to access textbox on a non-modal form

Ian3 61 Reputation points
2022-06-02T16:06:30.527+00:00

I tried to change text of textbox on a non-modal form after Start-Job executed but got error. Is there a way to access the form objects?

Function Form {
    [void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
    $Form        = New-object System.Windows.Forms.Form
    $TextBox1    = New-Object System.Windows.Forms.TextBox
    $TextBox1.Size = '60,25'
    $TextBox1.Location =  '90,28'

    $Form.Size = '300,300'
    $Form.Location = 'Center'
    $Form.Controls.Add($TextBox1)
    $Form.ShowDialog()
}
Start-Job $function:Form | Out-Null
$TextBox1.Text = 'ABC' # got error
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,626 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 35,191 Reputation points
    2022-06-02T19:03:00.457+00:00

    First, fix your code. Line 9 should be: $Form.StartPosition = [int][System.Windows.Forms.FormStartPosition]::CenterScreen (or omit the "[int]" cast). If you want to control the position of the form on the screen yourself you'd have to get the details about the hardware and then make provisions to change the coordinates if the window is resized.

    You haven't added any buttons to your dialog box, either. And ShowDialog produces a MODAL window -- your function won't return until you close the dialog or add the necessary button(s) so the function returns something other than "Cancel".

    Why are you using Start-Job to create the form and then not check the status of the job?

    Also, the variable $TextBox1 is local to the function -- it isn't available to the code that called the function.

    No comments