是否无法从非 UI 线程显示FolderBrowserDialog?

发布于 2024-09-03 13:04:14 字数 291 浏览 4 评论 0原文

我在显示从非 UI 线程创建和调用的 FolderBrowserDialog 实例时遇到问题。它无法正确渲染。

更具体地说,它不显示文件夹树,而是仅显示创建新文件夹 确定取消

alt text

I'm facing problem in showing FolderBrowserDialog instance created and called from a non-UI thread. It doesn't get renders properly.

Being more specific, it doesn't shows the folder tree but displays only the Make New Folder OK and Cancel

alt text

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鹿港巷口少年归 2024-09-10 13:04:14

所有外壳对话框(包括FolderBrowserDialog)都需要将线程的COM 单元设置为STA。您可能错过了 Thread.SetApartmentState() 调用:

    private void button1_Click(object sender, EventArgs e) {
        var t = new Thread(() => new FolderBrowserDialog().ShowDialog());
        t.IsBackground = true;
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

请注意,您无法设置对话框的所有者,它很容易在另一个应用程序的窗口后面丢失。这使得在工作线程上显示表单或对话框不是一个好主意。

All the shell dialogs, including FolderBrowserDialog, require the COM apartment for the thread to be set to STA. You are probably missing the Thread.SetApartmentState() call:

    private void button1_Click(object sender, EventArgs e) {
        var t = new Thread(() => new FolderBrowserDialog().ShowDialog());
        t.IsBackground = true;
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
    }

Beware that you cannot set the owner of the dialog, it easily gets lost behind a window of another application. Which makes showing forms or dialogs on a worker thread less than a good idea.

夏日浅笑〃 2024-09-10 13:04:14

我不确定你为什么要这样做。在工作线程上,计算所需的所有值都应该可用。应该不需要用户交互来获取更多输入。
也许重新设计对您的情况更有帮助。考虑在启动工作线程之前将选定的文件夹提供给它。

编辑(回复评论):
如果您想做一些记录,我的答案仍然适用。您的工作线程应该知道在哪里记录异常,而不是开始询问用户。
你使用日志框架吗?如果没有,请查看 log4net 。在这里,您通常会在 xml 文件中预先配置日志记录(日志级别、路径、格式……)。无需用户交互。尽管用户可以更改日志记录路径(在 xml 文件中)。

I am not sure why you would want to do this. On a worker-thread all neccessary values for your calculation should be available. There should be no need for user-interaction to get more input.
Maybe a redesign would be more helpful in your case. Think about providing the selected folder to your worker-thread before starting it.

EDIT (reply to the comment):
If you want to do some logging my answer still applies. Your worker-thread should know where to log exceptions and not start to ask the user.
Do you use a logging framework? If not, have a look at log4net for instance. Here you normally pre-configure your logging (the log-level, path, format, ...) in a xml-file. There is no user interaction needed. Though the user could change the logging path (in the xml file).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文