C#OpenFileDialog线程启动但对话框未显示

时间:2015-09-07 09:11:09

标签: c# multithreading folderbrowserdialog

我正在尝试完成我的静态Prompt类,以便能够从任何地方调用它。但问题是无法显示对话框。我已经在使用[STAThread],这是我的代码。

public static string ShowFileDialog()
{
    string selectedPath = "";
    var t = new Thread((ThreadStart)(() =>
    {
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
        fbd.ShowNewFolderButton = true;
        if (fbd.ShowDialog() == DialogResult.OK)
        {
            selectedPath = fbd.SelectedPath;
        }
    }));
    t.SetApartmentState(ApartmentState.STA);
    t.Start();

    t.Join();
    return selectedPath;
}

public static class Prompt是我的提示类。我是从public partial class Dashboard : Form

调用的

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

当你没有得到例外时,它肯定会正常工作。但是,是的,相当不错的几率你不会看到对话。非常难看的问题,你也没有任务栏按钮。找回它的唯一方法是最小化桌面上的其他窗口。

对话框任何对话框必须具有所有者窗口。您应该将该所有者传递给ShowDialog(所有者)方法重载。如果您没有指定它自己寻找所有者的那个。底层调用是GetActiveWindow()。为了得不到任何东西,桌面窗口现在变成了所有者。这还不足以确保对话窗口在前面。

至少你必须创建该所有者窗口,现在你至少要有任务栏按钮。像这样:

    using (var owner = new Form() { Width = 0, Height = 0,
        StartPosition = FormStartPosition.CenterScreen,
        Text = "Browse for Folder"}) {
        owner.Show();
        owner.BringToFront();
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
        fbd.ShowNewFolderButton = true;
        if (fbd.ShowDialog(owner) == DialogResult.OK) {
            selectedPath = fbd.SelectedPath;
        }
    }

仍然不保证对话框可见,当他与另一个窗口进行交互时,您无法将窗口推入用户的脸部。但至少那里有一个任务栏按钮。

我会非常犹豫地展示黑客,不要使用它:

    owner.Show();
    var pid = System.Diagnostics.Process.GetCurrentProcess().Id;
    Microsoft.VisualBasic.Interaction.AppActivate(pid);

吸引用户注意力并让他与你的UI互动的正确方法是NotifyIcon.ShowBalloonTip()。