Order of Activation

In one of my programs I fixed a bug. I just forgot to restore TopMost state of form. Fix was very simple, just set this.TopMost = true in form's constructor and everything is solved.

Like every simple fix, this one failed miserably. As soon as I "fixed it" I could not even start program. Even worse thing is that it failed where there was no error before. It didn't take much to deduce that this change was somehow responsible for triggering error in completely different part of code. It looked like just fact that I have TopMost turned on changes how rest of program is loaded.

I tested program without setting TopMost and order of triggering form's events was quite expected - first constructor, then Form_Load, then Form_Activated and Form_Shown. However, things do change when you set TopMost property.

It is a subtle change - contructor is still first one to complete, next one is Form_Activated, then Form_Load and Form_Shown is last once more.

If you have code in both Form_Load and Form_Activated you have a minefield in your code. Everything works as expected until you step on mine. In my case mine was TopMost property, but it is not only one that behaves like this.

Solution was dead simple - just move TopMost from constructor to Form_Load and everything works perfectly.

Sample for your testing can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *