Thursday, May 1, 2008

SetCompatibleTextRenderingDefault must be called before the first IWin32Window object is created in the application.

SetCompatibleTextRenderingDefault must be called before the first IWin32Window object is created in the application.

Problem Description
I encountered this error when attempting to start a project's exe file compiled under the Release configuration.



Analysis & Observations
The exe file compiled under the Debug configuration started without any problem and there were no error messages or exceptions.

Starting the Release version from Visual Studio (though F5 - start debugging), it worked fine as well.

The Main() function had the Application.SetCompatibleTextRenderingDefault method call in the second line before the Load method call. So, this should be working fine.


The application configuration file has been renamed deployed.

When starting the exe, the process shows for a second in the Task Manager and then disappears (which is not what I expected).

There is no pragma code or conditional compilation sections in the code that may not execute when running in Release Mode.

Problem Cause
After all these observations and some further investigation in the code, I have finally found the real problem. The MainFormController is a singleton and had a Form as an instance member. This form was being instantiated when the class was being loaded in the memory, well before the Application.SetCompatibleTextRenderingDefault and Load method calls.

Solution
I have changed the code to lazy initialization of the form, and thus, the form will be instantiated only when it is requested for the first time. Wohoooooo.

5 comments:

Anonymous said...

man great tip ! thanks a lot. In my case, the Program class had fields that were being initilized at class load-time (instead of using constructors). Initializing fields (i.e., a custom type) at load-time caused the same problem you speak about.

Bigot said...

I must thank you.
I had the same problem since few days. I also used a singleton and I would probably give up if I didn't find your tips. Once again, thanks a lot.

Anonymous said...

i also got this problem.
but resolved by only commenting the above code.

//Application.SetCompatibleTextRenderingDefault(false);
its working fine for me.
could anyone can point it out the exact problem?

Be Meo said...

i visited your site , it's very nice...wellcome to my blog ! thank you so much!
http://www.tech24h.us/

jeffj said...

This solved my problem exactly! Thanks so much for posting this.