title: Trying to close all opened forms in visual basic
body: <p>I want it so when my button is clicked, I exit my application. I tried a simple for loop:</p>
  
  <pre><code>Private Sub CloseAllToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseAllToolStripMenuItem.Click
      For Each Form In My.Application.OpenForms
          Form.Close()
      Next
  End Sub
  </code></pre>
  
  <p>But after closing all forms besides the form with this button on it, I get this error:</p>
  
  <blockquote>
    <p>An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll
    Additional information: Collection was modified; enumeration operation may not execute.</p>
  </blockquote>
  
  <p>I believe this is because I close the form executing the code before the loop can go to the next form. If this is the case, how can I make it so my loop finishes once the last form is closed? Can I even do that?</p>