Application.EnableVisualStyle has BUG??????????
Introduction
Version 1.1 of the .NET framework introduced the method system.Windows.Forms. Application.EnableVisualStyles. Calling this method prior to the creation of any Forms or Controls, will cause Windows XP to apply a theme when rendering Windows Common Controls and many of the native .NET controls like Buttons and CheckBoxes.
The introduction of EnableVisualStyles to v1.1 of the framework is a nice addition because it allows WinForms applications to easily adopt the new look and feel of Windows XP styles.
The Bug
The problem is that there is a bug in the implementation of EnableVisualStyles that interferes with Images stored in an ImageList component and Window Common Controls, like the TreeView or Toolbar classes. The effect is that if you call EnableVisualStyles, all of the images will disappear from your toolbars, treeviews and listviews.
To reproduce the bug:
- Create a WinForms application in VS.NET 2003
- Add a
Toolbar and ImageList to Form1
- Add an image to the
ImageList and a button to the Toolbar
- Assign the image to the button
- In the
Main method add a call to Application.EnableVisualStyles just before the call to Application.Run
When you run the app on Windows XP, with a Visual Style active, there will be no image on the toolbar button.
Solution(for C# only??)
After some searching from the google.com, I found some discussion of this issue and a work around that seems to work and hasn't caused any problems in C# applications.
A call to Application.DoEvents just after EnableVisualStyles, seems to fix the problem. How or why, who knows. Most likely it causes some message that was sent via PostMessage to get flushed out to the correct place, before the creation of the first WinForms based window.
So the work around code looks like this:
Sub Main()
Application.EnableVisualStyles()
Application.DoEvents()
Application.Run(Form1())
End Sub
However, I try to inplement this into VB.NET and it does not work at all. However, everyone are saying it works fine if under C#. Interesting.
Also, I read from someone called Michael Harsh who is from MS Team(I guess) and replying with the following message in some public forums.
====================================================
This is indeed a bug and will not be fixed for the final version of 2003. The problem is that the handle for the ImageList is being created prior to the the fusion binding context we setup around the app's main message pump. This is why ImageLists are broken everywhere (TabControl, TreeView, etc).
There are a few decent workarounds. The first is to either manually add a .manifest file to your .exe's directory, or embed one in the Win32 resource section of your .exe.
The other workaround is to move the code which creates your ImageList from InitializeComponent to the Form's Load event. This will delay the handle creation.
Good luck,
====================================================