ContextMenuStrip in Loop

Welcome Forums General PowerShell Q&A ContextMenuStrip in Loop

Viewing 1 reply thread
  • Author
    • #212136
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      <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?

      • This topic was modified 2 months ago by CMBlue64.
    • #212208
      Topics: 12
      Replies: 1610
      Points: 2,508
      Helping Hand
      Rank: Community Hero

      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
      $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++) {
          $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
              $this.BackColor = 'Gray'
          $btnY += 50
Viewing 1 reply thread
  • You must be logged in to reply to this topic.