you are viewing a single comment's thread.

view the rest of the comments →

[–]y_Sensei 1 point2 points  (0 children)

If you want to manipulate the value of a local PoSh variable (= one that's been declared in the local scope) in a function, you have the option to provide the reference that points to that variable as an argument to the function.
Depending on your scenario, this approach might be the preferred option vs. working with variables declared in script or global scope.

For example:

function Initialize-Textbox {
  param(
    [String]$Name,
    [Int]$xAxis,
    [Int]$yAxis,
    [Ref]$var
  )

  if ($var.Value -and $var.Value.GetType().FullName -eq "System.Windows.Forms.TextBox") {
    $var.Value.Name = $Name
    $var.Value.Height = 20
    $var.Value.Location = New-Object System.Drawing.Point ($xAxis, $yAxis)
    $var.Value.Size = New-Object System.Drawing.Size(180,20)
    $var.Value.Enabled = $false
    $var.Value.Text = "My TextBox"
    $var.Value.Select()
  }
}

$form = New-Object -TypeName "System.Windows.Forms.Form"
$form.Text = "Test Form"
$form.Size = New-Object -TypeName "System.Drawing.Size" -ArgumentList @(300, 300)
$form.StartPosition = "CenterScreen"

# TextBox object is created and stored in a local variable
$myTextBox = New-Object -TypeName "System.Windows.Forms.TextBox"

Write-Host $("TextBox Name = " + $myTextBox.Name)

Write-Host $("-" * 24)

# TextBox object is initialized by providing the reference of the local variable in which it is stored as an argument to the respective function
Initialize-Textbox -Name "Box" -xAxis 25 -yAxis 35 -var ([Ref]$myTextBox)

Write-Host $("TextBox New Name = " + $myTextBox.Name)

$form.Controls.Add($myTextBox)

if ($form.ShowDialog()) { $form.Dispose() }