ContextMenuStrip in Loop

<p style=“text-align: center;”>foreach ($file in $files) {</p>
<p style=“text-align: center;”> $b.Name=$file</p>
<p style=“text-align: center;”> $b=New-Object System.Windows.Forms.Button</p>
<p style=“text-align: center;”>$b.location= “$Across, $Up”</p>
<p style=“text-align: center;”> $b.Text="$file"</p>
<p style=“text-align: center;”> $b.Tag=$file</p>
<p style=“text-align: center;”>$Across = $Across + 80</p>
<p style=“text-align: center;”>$b.ContextMenuStrip = $contextMenuStrip1</p>
<p style=“text-align: center;”>$Duty.Add_Click{($b.Backcolor = “Green”)}</p>
<p style=“text-align: center;”>$WFH.Add_Click{($b.Backcolor = “Orange”)} }</p>
When I run this, it will only turn change the colour of the last button made. How can I make it so it will only change the colour of the button right clicked?

If you are dynamically creating buttons, you can use $this, which references the current object.

$computers = 'Comp1','Comp2','Comp3'

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

[System.Windows.Forms.Application]::EnableVisualStyles()

$Form            = New-Object system.Windows.Forms.Form
$Form.ClientSize = '400,400'
$Form.text       = "Test"
$Form.BackColor  = "#ffffff"
$Form.TopMost    = $false

$btnY = 50

for ($i=0;$i -lt $computers.Count;$i++) {
$computers[$i]
    $thisButton           = New-Object system.Windows.Forms.Button
    $thisButton.BackColor = "Green"
    $thisButton.text      = $computers[$i]
    $thisButton.width     = 200
    $thisButton.height    = 50
    $thisButton.location  = New-Object System.Drawing.Point(100,$btnY)
    $thisButton.Font      = 'Microsoft Sans Serif,12'
    $thisButton.ForeColor = "white"
    $thisButton.Visible   = $true
    $Form.Controls.Add($thisButton)
    $thisButton.Add_Click({
        $this.BackColor = 'Gray'
    })

    $btnY += 50
}

[void]$Form.ShowDialog()