I have a C# class library (.dll). I want to use it from a unmanaged C++ application through a managed C++ static library. The C# dll has a form which contains a COM component(WebBrowser) which requires the current thread to be in Single Thread Apartment model.
BUT the entry point is actually in the unmanaged C++ project, so I can't add any Thread attributes to my entry point. I have tried
CoInitialize, but it did not work.
I then created a new thread and set its state to STA. Then the thread loads the form. This works correctly, but there comes an error in event handling.
...
m_view->DocumentCompleted += gcnew WebBrowserDocumentCompletedEventHandler(this, &CLRWin::DocCompleted);
...
Void DocCompleted(Object ^s, WebBrowserDocumentCompletedEventArgs ^e)
{
MessageBox::Show("Doc Completed");
try
{
m_view->Document->MouseDown += gcnew HtmlElementEventHandler(this, &CLRWin::MouseEvt);
}
catch (Exception ^exc)
{
MessageBox::Show(exc->Message + " in object " + exc->Source);
}
}
The message box displays "Specified cast is not valid. in object System.Windows.Forms".
The above code works perfectly in a CLR Application without any separate thread(but with STAThread attribute).
Also, I don't want to create a separate thread for this purpose.
I don't want to turn on
Common Language Runtime support in my CLR project for many reasons.
Is there a way in native C++, to set the current thread's model to STA?
Thanks in advance.