C++/cli -> calling c# dll -> calling OpenFileDialog issue

◇◆丶佛笑我妖孽 提交于 2019-12-04 16:12:34

When you're a DLL you can't directly control the apartment your thread is running in - a thread can only be in one apartment at a time, and so if the thread that calls into your DLL is already some other apartment, then you can't change it.

Do you control the code that is calling your DLL? If not, then I think the best you can do is to start up your own thread (in which you can control the apartment it runs in, via CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)) and then call OpenFileDialog/SaveFileDialog from there.

Everyone,

Thanks for the help. For some reason starting a new thread never occurred to me.

Thanks everyone for that tidbit. Since I am already in IJW C++/cli land I thought it better to solve the problem using the .net framework.

Once I realized I needed a new thread, it was quite simple.

I moved my function that called the C# dll into a separate class:

ref class StaClass { public:

System::String^ strFile;
System::String^ strNote;

void CallWiki()
{
    WikiNotes::FrmWiki fw;

    fw.File = strFile;
    fw.Note = strNote;

    fw.ShowDialog();
}

};

and then from the main thread I used this code to spin up a STA Thread.

wiki->strFile = gcnew System::String(File);
wiki->strNote = gcnew System::String(Note);

ThreadStart^ threadDelegate = gcnew ThreadStart(wiki, &StaClass::CallWiki);
Thread^ newThread = gcnew Thread(threadDelegate, 0);
newThread->SetApartmentState(ApartmentState::STA);
newThread->Start();

Simple and easy to read and understand (At least for me - I'm a .Net programmer, I never delved much into COM, MFC and ATL)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!