1

How can I assign a link to each button? I can't manged it... I dont speak english well. Sorry for the translation...

$ButtonName =@('Option One', 'Option Two', 'Option Three') $i = 0 $ButtonName | foreach{ $CurrentButton = $null $CurrentButton = New-Object System.Windows.Forms.Button $CurrentButton.Location = "$(10+70*$i),35" $CurrentButton.width = 60 $CurrentButton.height = 60 $CurrentButton.Image = [System.Drawing.Image]::FromFile("c:\script\" + $ButtonName[$i] + ".jpg") $CurrentButton.Add_Click({Start-Process -FilePath "c:\script\" + $ButtonName[$i] + ".lnk"}) $i++ $Script.Controls.Add($CurrentButton) } 

$CurrentButton.Add_Click({Start-Process -FilePath "c:\script" + $ButtonName[$i] + ".lnk"}) does not work...

1

1 Answer 1

2

The problem here is that the event handler doesn't "remember" the value of $i at the time it was defined. To work around this, we can close over a local variable reference:

$ButtonNames = @('Option One', 'Option Two', 'Option Three') for($i = 0; $i -lt $ButtonNames.Count; $i++) { # assign value to local variable $ButtonName = $ButtonNames[$i] $CurrentButton = New-Object System.Windows.Forms.Button $CurrentButton.Location = "$(10+70*$i),35" $CurrentButton.Width = 60 $CurrentButton.Height = 60 $CurrentButton.Image = [System.Drawing.Image]::FromFile("c:\script\${ButtonName}.jpg") # after running `GetNewClosure`, the resulting scriptblock will "remember" the value of $ButtonName $CurrentButton.Add_Click({Invoke-Item "C:\script\${ButtonName}.lnk"}.GetNewClosure()) $Script.Controls.Add($CurrentButton) } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This is exactliy the right solution! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.