C# 如何在动态创建的表单中打开文件浏览器对话框?

C# 如何在动态创建的表单中打开文件浏览器对话框?,c#,.net,multithreading,user-interface,sta,C#,.net,Multithreading,User Interface,Sta,我的应用程序中有两个表单,一个在设计时生成,另一个在运行时动态生成。在运行时生成的表单中有一个上下文菜单,其中有一个打开FolderBrowserDialog的项。无论何时,我尝试点击该项目时,都会出现错误 Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThread

我的应用程序中有两个表单,一个在设计时生成,另一个在运行时动态生成。在运行时生成的表单中有一个上下文菜单,其中有一个打开
FolderBrowserDialog
的项。无论何时,我尝试点击该项目时,都会出现错误

  Current thread must be set to single thread apartment (STA) mode before OLE  

  calls can be made. Ensure that your Main function has STAThreadAttribute  

  marked on it. This exception is only raised if a debugger is attached to the  

  process.
如其他问题所述,上述问题的解决方案是将
Main()
方法标记为
[STA-Thread]
,但在我的例子中已经有了。那么,我如何纠正这个问题呢?
我调用对话框的方式是:-

    private void RightClickMenuClicked(object sender, ToolStripItemClickedEventArgs e)
    {
       if (e.ClickedItem.ToString() == "Copy")
        {
           FolderBrowsing.ShowDialog() ; 
           // Do other stuff here ....
        }
   }

我不知道您是如何调用
ShowDialog
方法的。您可以尝试下面的代码

    private DialogResult STAShowDialog(FolderBrowserDialog dialog)
    {
        DialogState state = new DialogState();
        state.dialog = dialog;
        System.Threading.Thread t = new  
               System.Threading.Thread(state.ThreadProcShowDialog);
        t.SetApartmentState(System.Threading.ApartmentState.STA);
        t.Start();
        t.Join();
        return state.result;
    }

    public class DialogState
    {
      public DialogResult result;
      public FolderBrowserDialog dialog;


      public void ThreadProcShowDialog()
      {
        result = dialog.ShowDialog();
      }
    }
然后在你的按钮上点击或者在你可以尝试的地方

     private void button1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog _myfolderDialog= new FolderBrowserDialog();
        frm.InitializeLifetimeService();


        DialogResult _result= STAShowDialog(_myfolderDialog);
        if (result== DialogResult.OK)
        {
            //Do your stuff
        }
    }

在Windows窗体或WPF中,用户界面只能在单线程中运行。您必须使用
Invoke
方法将额外的窗口调用封装到中-这将迫使UI线程处理它。(凯尔的方法有点类似)

你能发布一些关于如何做到这一点的代码吗?@Szymon我已经发布了一些代码。