I'm trying to generate a dynamic UI. I haven't been able to add an OnClick event dynamically. Here's a sample
function Say-Hello
{
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]$name
)
Write-Host "Hello " + $name
}
$name = "World"
$null = [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$mainform = New-Object System.Windows.Forms.Form
$b1 = New-Object System.Windows.Forms.Button
$b1.Location = New-Object System.Drawing.Point(20, 20)
$b1.Size = New-Object System.Drawing.Size(80,30)
$b1.Text = "Start"
#$b1.Add_Click({Say-Hello $name})
$b1.Add_Click({Say-Hello $name}.GetNewClosure())
$mainform.Controls.Add($b1)
$name = "XXXX"
$mainform.ShowDialog() | Out-Null
First I've tried with $b1.Add_Click({Say-Start $name}) but that yields Hello XXXX. I then tried the above code as it is $b1.Add_Click({Say-Hello $name}.GetNewClosure()) and I got an error that Say-Hello is not found (Say-Hello : The term 'Say-Hello' is not recognized as the name of a cmdlet, function, script file...)
The reason I'm overriding the name, is because I actually want to turn the button creation to a function that I will call several ties, each time with a different $name parameter.
Any suggestions how to handle this?
thanks
Hello WorldorHello XXXXon the console? When I run your code I seeHello + Worldprinted to the console (although you probably want to useWrite-Host ("Hello " + $name)orWrite-Host "Hello $name"instead)Hello XXXX. I'm trying to getHello World@mklement0 answer explains itWrite-Hostwas an aside to point out a syntax problem:Write-Host 'hi ' + 'there'prints verbatimhi + there, because the lack of(...)enclosure around the+operation means that three separate arguments are passed. As for the answer: glad to hear it explains your intent, but does it also solve your problem?