c# - 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。仅当调试器附加到进程时才会引发此异常。”
解决方案
推荐阅读
- image - Flutter 应用中的 webP 动画图像会在 iOS 上显示吗?
- python - 散景工具提示获得 Y 值顶部
- angular - 如何使用 Angular 8 删除/更新 Firebase 实时数据库(AngularFireDatabase)中的数据?
- excel - 在 Excel 中拆分和比较连接的字符串
- android - 如何在应用程序运行时在房间里制作多个多张桌子?
- c# - 如何在两个控制器之间传递数据
- c++11 - 元组索引超出范围
- python - 与 Visual Studio 相比,Scope 在 Databricks 上的行为似乎不同(对于相同的 Python 代码)
- python - 当 div 为空时,XPath 设置默认值
- sql - PL/SQL 更改过程中 1 行中的值