does VB6 allow referencing Form instance as a sing

2019-06-24 10:47发布

问题:

I am seeing code like "Unload frmMain" where from what I can tell frmMain is the type/module name, and I don't think it could also be simultaneously a variable name of the "ObjFrmMain" sort. Nevertheless, this command does successfully induce the form in question to unload.

So is the data type being used as an alias for its single existing instance? Or maybe for all of its instances?

Does VB6 do similar things to data types other than those derived from Form?

回答1:

Yes, VB6 has odd object behavior. It gives you some shortcuts for dealing with form objects.

Load frmMain

...will load a single instance of that form under that variable name. In fact:

frmMain.lblSomeLabel.Caption = "some caption"

... will load that instance. However:

frmMain.SomeStringMember = "some value"

... will not load the form object (meaning the window itself) but you can access these variables, so in essence, the name of the form is a global variable.

You can, however, create new instances:

Dim newForm As MyForm
Set newForm = New MyForm
newForm.Show vbModal

That will actually create a new instance of MyForm, load it and show it, so you can have multiple instances of one form.

Also beware of the oddness in the New keyword:

Dim newObject As New MyClass
Set newObject = Nothing
newObject.SomeStringProperty = "some value"

This works without an "Object Reference Not Set ..." error. When you declare a reference variable using the As New syntax, you can destroy the object by setting it to Nothing and then reference that variable again and it will create a new instance.

In fact that's what's really going on with the forms. There is an implicit:

Dim frmMain As New frmMain

Personally I prefer not to use the As New syntax because it's confusing and dangerous. It also has a performance penalty, vs. this:

Dim newObject As MyClass
Set newObject = New MyClass

... but you're stuck with it for the forms.

What's happening when you call Unload frmMain is that it unloads the window (and all the controls) so all the data in those are gone, but the object frmMain is still hanging around. Therefore even after you unload it, you can still access any member variables and properties. However, if anything references any control on the form, it will trigger an implicit Load frmMain. This is the source of a lot of subtle programming errors in VB6, especially when you're trying to shut down.



回答2:

Yes, it's a special functionality in VB6 and earlier. I normally tried to avoid doing it, since I saw it more as a source of confusion rather than a help.

The following comment In Visual Basic 6.0 and earlier versions, a special default instance of each form is automatically created for you, and allows you to use the form's name to access this instance. is taken from this MSDN page: Working with Multiple Forms in Visual Basic .NET: Upgrading to .NET



标签: oop vb6