7

I want it so when my button is clicked, I exit my application. I tried a simple for loop:

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

But after closing all forms besides the form with this button on it, I get this error:

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute.

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?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Klink45
  • 439
  • 1
  • 6
  • 21

3 Answers3

13

Close all but current form:

My.Application.OpenForms.Cast(Of Form)() _
              .Except({Me}) _
              .ToList() _
              .ForEach(Sub(form) form.Close())

Close application normally:

Application.Exit()

Force application to exit:

Environment.Exit(1)
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Can you explain the reason behind `Environment.Exit(1)`? As my understanding that is used for console based applications... Also if you don't have the permission flag you will throw a security exception. – Trevor Jan 18 '16 at 00:26
  • @Codexer [`Environment.Exit`](https://msdn.microsoft.com/en-us/library/system.environment.exit(v=vs.110).aspx) Terminates this process and returns an exit code to the operating system. – Reza Aghaei Jan 18 '16 at 00:30
  • I know what it does but why doesn't Application.Exit suffice enough? – Trevor Jan 18 '16 at 00:31
  • 2
    @Codexer The difference is between close gently or force to exit (kill). For example, put a message box in closing event of some forms and ask about if you really want to close the form and set `e.Cancel=true` to see the difference. – Reza Aghaei Jan 18 '16 at 00:33
  • @Codexer You are welcome:) Hope you find the answer useful :) – Reza Aghaei Jan 18 '16 at 00:39
1

This is simple, just add a validation:

        For Each Form In My.Application.OpenForms
            If Form.name <> Me.Name Then
                Form.Close()
            End If
        Next
1

what this does is close all form except "exceptthisform" or the mainform

     Dim formNames As New List(Of String)

        For Each currentForm As Form In Application.OpenForms

            If currentForm.Name <> "exceptthisform" Then

                formNames.Add(currentForm.Name)

            End If

        Next

        For Each currentFormName As String In formNames
            Application.OpenForms(currentFormName).Close()

        Next
Adam
  • 147
  • 1
  • 13