如何正确使用openfiledialog

本文关键字:openfiledialog 何正确 | 更新日期: 2023-09-27 17:59:23

我正在学习如何使用OpenFileDialog;这是我正在使用的代码:

using System;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Reflection;
namespace my_album
{
    class Program
    {
        static void Main()
        {
            MyForm album = new MyForm();
            Application.Run(album);
        }
    }
    public class MyForm : Form
    {
        private Button btnLoad;
        private PictureBox pboxPhoto;
        public MyForm()
        {
            Size = new Size(400, 400);
            Text = "Hello Form";
            Button btnLoad = new Button();
            btnLoad.Text = "&Load";
            //btnLoad.Location = new Point(20, 20);
            //b.Size = new Size(20, 30);
            btnLoad.Left = 10;
            btnLoad.Top = 10;
            btnLoad.Click += ButtonClickHandler;
            pboxPhoto = new PictureBox();
            pboxPhoto.BorderStyle = BorderStyle.Fixed3D;
            pboxPhoto.Width = Width / 2;
            pboxPhoto.Height = Height / 2;
            pboxPhoto.Left = (Width - pboxPhoto.Width) / 2;
            pboxPhoto.Top = (Height - pboxPhoto.Height) / 2;
            pboxPhoto.SizeMode = PictureBoxSizeMode.StretchImage;
            Controls.Add(pboxPhoto);
            Controls.Add(btnLoad);
        }

        private void ButtonClickHandler(object sender, EventArgs e)
        {
            Console.WriteLine("kkk");
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = @"c:'";
            dlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine("open ok");
            }
            dlg.Dispose();
        }
        public override sealed string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }
    }
}

每当我按下加载按钮时,程序就会关闭。为什么?

如果我用dlg.ShowDialog()注释这行,它会起作用,所以这一定是错误,但我不知道如何修复它。

我使用的是c#和Visual Studio 2012

如何正确使用openfiledialog

dlg.Dispose();对控件是冗余的,因为它是在控件内部处理的。当您选择一个文件时,程序可以尝试锁定它,如果您在程序中的其他地方使用所选文件,可能会导致问题。如果出于某种原因,您确实需要检查资源是否已关闭,那么您可以将其更改为

if (dlg != null)
   {
       dlg.Dispose();
   }

如果发生了其他意外错误,那么在代码周围放一个try-catch会捕获它,并为您提供更多信息。

    private void ButtonClickHandler(object sender, EventArgs e)
    {
        Console.WriteLine("kkk");
        try
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = @"c:'";
            dlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine("open ok");
            }
        } catch (Exception ex)
        {
            Console.WriteLine("Dialog open error occurred: " + ex.Message);
        }
    }