According to MSDN:
When you access Form through My.Forms.Form1, the factory method checks to see if an instance of Form1 is already open. If it is, that instance is returned. Otherwise, an instance of Form1 is created and returned.
So essentially it is created and Sub New
called just before it is shown (not created somewhere and held until needed). The link includes this code showing how it creates those default instances:
'Code ... generated by the compiler
Public m_Form1 As Form1
Public Property Form1() As Form1
Get
m_Form1 = Create__Instance__ (Of Form1)(m_Form1)
Return m_Form1
End Get
Set(ByVal Value As Form1)
If Value Is m_Form1
Return
End If
If Not Value Is Nothing Then
Throw New ArgumentException("Property can only be set to Nothing.")
End If
Dispose__Instance__ (Of Form1)(m_Form1)
End Set
End Property
However, you are talking about the default ("weird") instance method which is ill-advised to begin with. This largely exists to provide compatibility with VB6 type code where you did just do myForm.Show()
to instance and show a form (and probably for tinkerers who do not really understand instancing or OOP).
Forms are classes and should be treated as such by explicitly creating instances; so, generally:
Dim frm As New frmMain ' NEW creates the instance
frm.Show
You can set a breakpoint on InitializeComponent
in the form's Sub New
to see when it is invoked. To create a global reference to it, like you might with any other class:
Friend frmMain As MainForm ' no instance yet
Friend myMain As MainClass
Public Sub Main
' do this before any forms are created
Application.EnableVisualStyles()
myMain = New MainClass()
myMain.DoStuff()
frmMain = New MainForm() ' instanced (NEW)
Application.Run(frmMain)
End Sub
Likewise:
Dim frm2 = New frmNotMain ' declare and instance
' short for:
Dim frm2 As frmNotMain ' declare frm2
frm2 = New frmNotMain ' create instance
frm2.Show
In all cases, Sub New
for your form(s) would be called when you use the New
operator to create a New form. VB tries to make this clear thru the repeated use of New
, but with the default instance all that is actually tucked away in the form factory.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…