title: How to disable a Powershell GUI button during code execution?
body: <p>I can't get a button to be disabled during a function operation. If I disable it when the button is clicked, visually it looks disabled but it still works (or rather it queues the click).</p>
  
  <p>This is the working demo code I'm testing it on:</p>
  
  <pre><code>Add-Type -AssemblyName System.Windows.Forms
  [System.Windows.Forms.Application]::EnableVisualStyles()
  
  $Form                            = New-Object system.Windows.Forms.Form
  $Form.ClientSize                 = '400,400'
  $Form.text                       = "Form"
  $Form.TopMost                    = $false
  $Button1                         = New-Object system.Windows.Forms.Button
  $Button1.text                    = "button"
  $Button1.width                   = 100
  $Button1.height                  = 25
  $Button1.enabled                 = $true
  $Button1.location                = New-Object System.Drawing.Point(214,59)
  $Button1.Font                    = 'Microsoft Sans Serif,10'
  
  $Form.controls.AddRange(@($Button1))
  
  Function Test {
      Write-Host "Clicked"
      $Button1.Enabled = $false
      Start-Sleep -Seconds 2
      $Button1.Enabled = $true
  }
  
  $Button1.add_Click(
      {
          Test
      }
  )
  [void]$Form.ShowDialog()
  </code></pre>
  
  <p>I have tried putting in <code>[System.Windows.Forms.Application]::DoEvents()</code> and <code>button1.Update()</code> in the function. </p>
  
  <p>I've tried disabling the button in an initial function and then calling the part that takes longer in a separate function from the button click but that didn't work either. i.e.:</p>
  
  <pre><code>Function DisableBtn1 {
      $Button3.Enabled = $false
  }
  
  Function DoStuff {
      Write-Host "Bt1 Clicked"
      Start-Sleep -Seconds 2
      $Button3.Enabled = $True
  
  }
  
  $Button1.add_Click(
      {
          DisableBtn3
          DoStuff
      }
  )
  </code></pre>
  
  <p>Is there something obvious I'm missing in terms of making a GUI element properly disabled while a script is running?</p>