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

Ahm*_*ven 3 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;
}
Run Code Online (Sandbox Code Playgroud)

public static class Prompt是我的提示班.我是从public partial class Dashboard : Form课堂上打电话来的

谢谢你的帮助.

Han*_*ant 6

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

对话框,任何对话框,都必须具有所有者窗口.您应该将该所有者传递给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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

    owner.Show();
    var pid = System.Diagnostics.Process.GetCurrentProcess().Id;
    Microsoft.VisualBasic.Interaction.AppActivate(pid);
Run Code Online (Sandbox Code Playgroud)

引起用户注意并让他与UI交互的正确方法是NotifyIcon.ShowBalloonTip().