Click here to Skip to main content
15,886,794 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
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.
C#
...
// inside the constructor
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.
Posted
Comments
[no name] 22-Jun-14 7:34am    
"in native C++, to set the current thread's model to STA", AFAIK, you do not have to do anything. native C++ applications are single threaded by default.
Sergey Alexandrovich Kryukov 22-Jun-14 15:17pm    
This is absolutely not true. 1) Applications can be multithreaded and often are; 2) STA does not mean single-threaded; this is a model of thread collaboration; STA is the most limited which simplifies programming but limits it.
—SA

1 solution

some google search could done this job.

Explanation in MSDN

Best is on a blog:
http://blogs.msdn.com/b/adam_nathan/archive/2003/07/18/56727.aspx[^]

You need to call CoInitialize for STA.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900