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

C# OpenFileDialog Thread start but dialog not shown

我正在尝试完成我的静态提示 class 以便能够从任何地方调用它。但问题是无法使对话框显示。我已经在使用 [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 是我的提示 Class。我从 public partial class Dashboard : Form class

调用它

感谢您的帮助。

当你没有得到异常时,它肯定工作得很好。但是,是的,您看不到对话框的可能性很大。非常难看的问题,你也没有任务栏按钮。找回它的唯一方法是最小化桌面上的其他 windows。

一个对话框,任何 个对话框,必须有一个所有者window。您应该将该所有者传递给 ShowDialog(owner) 方法重载。如果你不指定它自己去寻找所有者。底层调用是 GetActiveWindow()。不出所料,桌面 window 现在成为所有者。这不足以确保对话框 window 在前面。

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

    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;
        }
    }

仍然不能保证对话框可见,当用户与另一个 window 交互时,您不能将 window 推到用户的脸上。但至少有一个任务栏按钮。

我会非常犹豫地展示它的破解方法,不要使用它:

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

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