如何在C ++中解决此COM问题?

时间:2014-06-22 04:43:38

标签: c# multithreading c++-cli

我有一个C#类库(dll),我希望从非托管C ++应用程序通过托管C ++静态库使用它。

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

C#dll有一个带有WebBrowser控件的表单,它是一个COM组件,问题出在那里。现在,我应该通过托管C ++静态库调用表单,当我这样做时,

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.

发生此错误。是的,这是由于当前线程不在单线程单元模型中。但我无法将任何线程属性添加到我的入口点,因为该项目是一个非托管项目。

我还尝试创建一个新线程,打开表格,如here所述。它工作正常,但是当我这样做时,WebBrowser控件似乎没有响应事件。所以我不想创建一个新线程。那么有没有办法将当前运行的线程更改为STA。另一个原因是我根本不想创建一个单独的线程。

我也尝试了 CoInitialize ,但我无法解决这个问题。

我无法将STAThread属性添加到入口点,作为非托管C ++项目中的入口点。

由于某种原因,我不想在我的非托管项目中启用公共语言运行时支持。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:0)

继续将[STAThread]添加到应用程序的主条目,这表明COM线程模型是单线程单元(STA)

示例:

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