0

I'm a "noobie" in scripting (ok, I'm particully a noob with windows form...) and I actually try to create a powershell function to "dynamically" generate a form.

I wish like, for exemple, I could write :

MyFunction -ButtonList "Button1,Button2,Button3"

And obtain this : Result Form

And when I click on a button I want to get button name (totaly useless, yes, but it's a training.)

My problem is I don't know how automaticaly generate buttons... I try this :

$i=0
foreach($Button in $ButtonList)
    {
    $CurrentButton = $null

    $CurrentButton = New-Object System.Windows.Forms.Button
    $CurrentButton.Location = "125,$(100+50*$i)"
    $CurrentButton.size = '250,35'
    $CurrentButton.Text = $Button
    $CurrentButton.Font = New-Object System.Drawing.Font ($Police,$ButtonSize,[System.Drawing.FontStyle]::Regular)
    $CurrentButton.add_click({$Script:Result = $CurrentButton.Text ;$form.Close()})
    $form.Controls.Add($CurrentButton)
    $i++
    }

But whatever which button a select, I alway get same result = name of last button create ("Button3" in this exemple)

I suppose problem come from $CurrentButton.add_click({$Script:Result = $CurrentButton.Text ;$form.Close()}) But I don't know how fix it...

thank you in advance for help !

1 Answer 1

1

Use $this.Text instead of $CurrentButton.Text.
The variable $CurrentButton is unknown in the click handler. There you can use the automatic variable $this that is a reference to the button control object itself.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know this automatic variable. Thank a lots !
@Mira Glad to have helped. If you feel my answer solved your problem, please mark it by clicking the checkmark icon to the left.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.