1

I have a C# class library(dll) which I want use from a unmanaged C++ application through a managed C++ static library.

 Unmanaged C++ Project(.exe) --> Managed C++ Project(.lib) --> C# Class Library(.dll)

The C# dll has a form with a WebBrowser Control which is a COM component, where the problem is. Now, I should invoke the form through the managed C++ static library, when I do so,

Unhandled Exception: System.Threading.ThreadStateException: ActiveX control '885
6f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current th
read is not in a single-threaded apartment.

This error occurs. Yes, this is due to the current thread not in the Single threaded apartment model. But I can't add any thread attribute to my entry point as the project is an unmanaged project.

I also tried to create a new thread that opens the form like described here. It worked, but when I do so, the WebBrowser control doesn't seem to respond to events. So I don't want to create a new thread. So is there a way to change the current running thread to STA. And another reason is I don't want to create a separate thread at all.

I also tried CoInitialize, but I can't solve this issue.

I can't add STAThread attribute to the entry point, as the entry point it is in an unmanaged C++ project.

I don't want to turn on Common Language Runtime support in my unmanaged project for some reason.

Is there any way to solve this issue?

Community
  • 1
  • 1
Alex
  • 245
  • 1
  • 2
  • 6
  • You *must* call CoInitializeEx() yourself in your main() function. And pump a message loop, hard requirement for an STA thread and WebBrowser will fail to work correctly when you don't. If your native program cannot provide those guarantees then it is not a suitable host for a browser and you *must* start your own thread. – Hans Passant Jun 22 '14 at 09:15

1 Answers1

0

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Single-threaded apartment - cannot instantiate ActiveX control

Why an ActiveX Control on a Managed Window Form Must Be STA-based

Community
  • 1
  • 1
Faisal
  • 364
  • 1
  • 8
  • No, I can't add STAThread Attribute to the entry point as it is an unmanaged C++ project. – Alex Jun 22 '14 at 05:41
  • I want to do something equivalent to STAThread attribute in native C++ project. That's why I asked this question. – Alex Jun 22 '14 at 05:52