如何在本机C ++项目中启用STA? [英] How to enable STA in native C++ project?

查看:107
本文介绍了如何在本机C ++项目中启用STA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#类库(.dll)。我想通过托管C ++静态库从非托管C ++应用程序中使用它。 C#dll有一个包含COM组件(WebBrowser)的表单,它要求当前线程处于单线程单元模型中。 但是入口点实际上是在非托管C ++项目中 ,所以我无法将任何Thread属性添加到我的入口点。我尝试了 CoInitialize ,但它没有用。



然后我创建了一个新线程并将其状态设置为STA。然后线程加载表单。这可以正常工作,但在事件处理中出现错误。

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.

...
// 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);
     }     
}



消息框显示指定的强制转换无效。在对象System.Windows.Forms中。以上代码在CLR应用程序中完美运行,没有任何单独的线程(但具有STAThread属性)。



另外,我不想创建单独的线程为了这个目的。



由于种种原因,我不想在我的CLR项目中打开公共语言运行时支持



在原生C ++中是否有办法将当前线程的模型设置为STA?



提前感谢。


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.

推荐答案

一些谷歌搜索可以完成这项工作。



MSDN中的解释



最佳博客:

http://blogs.msdn.com/b/adam_nathan/存档/ 2003/07/18 / 56727.aspx [ ^ ]



您需要致电 CoInitialize for STA。
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.


这篇关于如何在本机C ++项目中启用STA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆