How to access textbox on a non-modal form

Ian3 66 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 for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rich Matheisen 48,026 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.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.