在 wpf 中显示 System.Windows.Forms.FolderBrowserDialog 时出现异常
我尝试在 wpf 中显示 folderbrowserdialog
但出现此异常
当前线程必须设置为单线程 OLE 之前的线程单元 (STA) 模式 可以拨打电话。确保您的 Main函数有STAThread属性 标记在其上。此例外仅 如果附加了调试器则引发 流程
但没有更改如何解决此异常?
其功能是:
private void Save_any_File()
{
System.Windows.Forms.FolderBrowserDialog get_location = new System.Windows.Forms.FolderBrowserDialog();
get_location.ShowDialog();
}
I tried to show folderbrowserdialog
in wpf but I got this exception
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
I tried to add [STAThread] before this function but no change how can I solve this exception ?
The function is :
private void Save_any_File()
{
System.Windows.Forms.FolderBrowserDialog get_location = new System.Windows.Forms.FolderBrowserDialog();
get_location.ShowDialog();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 Main() 函数已经具有 [STAThread] 属性,它隐藏在 WPF 自动生成的代码中。除了 Main() 方法之外,它对其他任何地方都没有任何影响。它确保 WPF 应用程序的主线程(也称为 UI 线程)创建“单线程单元”。这是由 CLR 在应用程序中的任何代码开始运行之前完成的。
STA 是 UI 线程的硬性要求,许多 COM 组件都需要它。 STA 为非线程安全的软件提供了一个安全的家。因此是“单线程”。 OpenFileDialog 就是这样的组件之一,其他组件还有剪贴板和拖放支持。
还有许许多多的 COM 组件试图在您的应用程序中找到一个家。对于 OpenFileDialog,这些是自定义文件夹视图外观的 shell 扩展。
长话短说,问题毫无疑问是您正在尝试在工作线程上显示对话框。没有可以做的。使用 Dispatcher.BeginInvoke() 封送对 UI 线程的调用。
Your Main() function already has the [STAThread] attribute, it is buried in the auto-generated code for WPF. It doesn't have any effect anywhere else but on the Main() method. It ensures that the main thread of the WPF app (aka UI thread) creates a "single-threaded apartment". This is done by the CLR, before any code in your app starts running.
STA is a hard requirement for UI threads, many COM components require it. An STA provides a safe home for software that isn't thread-safe. Thus "single-threaded". The OpenFileDialog is one such component, others are the clipboard and drag+drop support.
And the many, many COM components that try to find a home in your app. In the case of OpenFileDialog, those are the shell extensions that customize the appearance of the folder view.
Long story short, the problem is no doubt that you are trying to display the dialog on a worker thread. No can do. Use Dispatcher.BeginInvoke() to marshal calls to the UI thread.
这篇文章可能会有所帮助。这是一个 Windows 窗体对话框,您通常需要 WindowsFormHost 或其他互操作方法。
This post may be helpful. That's a Windows Forms dialog, you generally need a WindowsFormHost or other interop method.