Why is an event firing during compilation of a VB6

2019-01-25 14:24发布

问题:

I am trying to compile a VB6 application, but it fails with the error, "Run-time error '91': Object variable or With block variable not set". It turns out the Resize event of a user control is firing during compilation and calling code that attempts to access an object that has not been instantiated yet.

Why is an event firing during compilation and is there any way to stop it?


Edit: I had some code here, but it's not relevant. The problem results from the fact that UserControl code (namely the Initialize, ReadProperties, Resize, and WriteProperties events) can execute at unexpected times. If the code in these events relies on other code to initialize any of its data structures, there's a good chance it's going to fail because that initialization code may not have executed. Especially during compilation when nothing is supposed to be executing! I'd call this a bug, but I'm sure Microsoft can rationalize it somehow.

回答1:

Here's is a good article on the lifecyle of user control events

Understanding Control Lifetime and Key Events

Here is one snippet

Compiling the Project

When the project is compiled into an application or component, Visual Basic loads all the form files invisibly, one after another, in order to write the information they contain into the compiled file. A control instance gets the Initialize, ReadProperties, and WriteProperties events. The control's property settings are compiled into the finished executable.

It doesn't mention resize (which happens during run-time or when you physically resize the usercontrol on a container in design-time). Maybe your Initialize event is resizing the user control?

To avoid the error you can check if the offending object has been created before doing anything:

If Not Object Is Nothing then
  do something


回答2:

I think some events for user controls get executed during design time, at least for the purpose of rendering them in a consistent way.