winforms 'OpenFileDialog'随机崩溃,直到Windows重置后才重新工作

jqjz2hbq  于 12个月前  发布在  Windows
关注(0)|答案(1)|浏览(102)

OpenFileDialog.ShowDialog()不生成新窗口的可能性很小,我的程序已经死了。在一次崩溃之后,它总是发生。重新启动程序并不能解决问题。任务管理器也没有响应,所以我无法检查导致崩溃的原因。我唯一能做的就是重新启动windows。有时我在崩溃后的操作会导致windows重新启动'explorer.exe'(从重启的情况来看),我可以再次使用OpenFileDialog
我使用的是WIN10(已更正,不是WIN7)/VS 2022(已更正,不是2023)Community/C#/.NET Framework 4。当我使用C++/Cli时,我通过添加.ShowHelp = true找到了一个解决方案,可以避免这种崩溃。但它在C#中不起作用。

namespace name1
{
    public partial class Form1 : Form
    {
        void ClickLoad(object sender, EventArgs e)
        {
            OpenFileDialog Open1 = new OpenFileDialog();
            Open1.Title = "Select the File to Load";
            Open1.InitialDirectory = StringInitialPath;
            Open1.Filter = "Text Files|*.txt|All files|*.*";
            Open1.ShowHelp = true;  //avoid crash for C++/Cli, but not here
            if (Open1.ShowDialog() == DialogResult.OK)  //it crashes right here
            {
                ......
            }
        }
    }

    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
        }
    }
}

这个问题的原因是什么,我如何避免它?
编辑:Adding a screenshot for shell extension

iqih9akk

iqih9akk1#

尝试使用using语句创建OpenFileDialog,以便在用户选择文件时立即处理分配给文件选取过程的内存。

void ClickLoad(object sender, EventArgs e){
 //try a using statement to define the open file dialog
 using(var Open1 = new OpenFileDialog()){
   Open1.Title = "Select the File to Load";
   //passing a bad parameter below could cause a crash
   Open1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
   Open1.Filter = "Text Files|*.txt|All files|*.*";
    //show the dialog 
   if(Open1.ShowDialog() == DialogResult.OK){
     //TO DO
    }
 }
}

也尝试删除行Open1.ShowHelp = true,它可能不支持在您的操作系统。

相关问题