views:

3003

answers:

4

In the middle of converting VB6 code to VB.NET, I need to replace the following code that intends to close all open forms remaining in the application.

'close all sub forms
For i = My.Application.OpenForms.Count - 1 To 1 Step -1
    'UPGRADE_ISSUE: Unload Forms() was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="875EBAD7-D704-4539-9969-BC7DBDAA62A2"'
    Unload(My.Application.OpenForms(i))
Next i

I've replaced the Unload function with Close (as indicated by TFM), but the compiler complains that OpenForms is not a member of My.Application.

Where can I access the open forms?

A: 

Have a look at the Application.Windows property.

Franci Penov
+3  A: 

Application.Exit will pretty much do the same.

AS I suppose you want to close the application anyway if all forms are closed.

chrissie1
pulling out the power plug will achieve the desired result as well. nevermind the few side effects... :-)))
Franci Penov
+1 for that often missed point. ;-)
Cerebrus
The Form.Closed and Form.Closing events are not raised when the Application.Exit method is called to exit your application. If you have validation code in either of these events that must be executed, you should call the Form.Close method for each open form individually before calling Exit method.
MarkJ
+6  A: 

The OpenForms property returns a FormCollection. You can iterate through the collection to process all forms.

For each f as Form in My.Application.OpenForms
 f.Close()
Next
Cerebrus
Its strange, I saw many people saying that this worked for them in VS 2005. My compiler refuses to acknowledge OpenForms (VS 2008)... Could it have been changed between the two versions??
brass-kazoo
It's in the VS 2008 documentation. http://msdn.microsoft.com/en-us/library/eh13dca9.aspx
MarkJ
Just tried it in VB2008 EXpress Edition. It works for me - does exactly what it says on the tin
MarkJ
I see no reason for it not to work. What error does your compiler raise?
Cerebrus
The error is: 'OpenForms' is not a member of 'i_hi002.My.MyApplication'.
brass-kazoo
So All I was missing (thanks to person-b's comment) was the import - 'Imports System.Windows.Forms'!
brass-kazoo
+1  A: 

I uncovered this solution,

'close all sub forms
For i = System.Windows.Forms.Application.OpenForms.Count - 1 To 1 Step -1
    Dim form As Form = System.Windows.Forms.Application.OpenForms(i)
    form.Close()
Next i

...which looks alright (if not verbose), and I'll be able to test it just as soon as I can compile everything else..

brass-kazoo
This is another way of applying for-each (with a slight performance difference for large number of iterations).
Cerebrus
You can just use Application.OpenForms, as usually you have 'Imports System.Windows.Forms' anyway.
Lucas Jones
Ahh... Thats what I was missing, the import!
brass-kazoo