Wednesday, May 13, 2009

Embedding .NET in an otherwise native application

For reasons best known to the company I work for we embed the .NET CLR inside our otherwise native C++ MFC-based application, and for the last two weeks I've been trying to nail down why pretty much everything seems to work, except the windows where we embed the WebBrowser control via COM.  No matter what I tried, IOleObject::SetClientSite() would fail and the web browser would display as an empty white rectangle on the desktop instead of in our window.

This guy seemed to have a very similiar symptom, but no answer; however, it was a fair guess he had the same problem and it was something to do with threading.

One of the guys at AutoDESK Developer Support (thanks again) pointed out that the CLR initialises the main thread to use MTA (multi-thread-apartment) mode, whereas the WebBrowser control really only works with STA (single-thread-apartment) mode.  So, the solution was to ensure that I called CoInitialize(NULL) in our main thread before the CLR had a chance to mess things up.