首页 > 解决方案 > OpenFileDialog 显示在启动它的 Windows 应用程序之外

问题描述

为了避免 STA 出现异常,这是我用来启动 OpenFileDialog 的代码。它工作正常,只是对话框是在应用程序之外打开的。有没有办法可以设置父/句柄,以便 OpenFileDialog 显示在应用程序中?感谢你的帮助。

Thread t = new Thread ((ThreadStart)(() => {

    OpenFileDialog openFileDialogBrowser = new OpenFileDialog();
    if (openFileDialogBrowser.ShowDialog() == DialogResult.OK)
    {
        selectedPath = openFileDialogBrowser.FileName;

    }
}));

// Run your code from a thread that joins the STA Thread
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
Console.WriteLine(selectedPath);

如果我在不创建新线程的情况下使用,则会出现以下异常:

“在进行 OLE 调用之前,必须将当前线程设置为单线程单元 (STA) 模式。确保您的 Main 函数上标记了 STAThreadAttribute。仅当调试器附加到进程时才会引发此异常。”

标签: c#winformsopenfiledialog

解决方案


推荐阅读