C#中Windows 窗体应用(.NET 8)对话框类SaveFileDialog 、OpenFileDialog、ColorDialog、FontDialog和FolderBrowserDialog

本文详细介绍了.NETFramework中的SaveFileDialog、OpenFileDialog、ColorDialog、FontDialog和FolderBrowserDialog五个对话框类的使用示例,以及它们与控件的区别,包括类的复杂性和控件的简单性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

一、SaveFileDialog 类

1.源码示例

2.生成效果

二、OpenFileDialog类

1.源码示例

2.生成效果

三、ColorDialog类

1.示例源码

2.生成效果

四、FontDialog类

1.源码示例

2.生成效果

五、FolderBrowserDialog类

1.示例源码

2.生成效果

六、总结:组件(控件)和类的差别


        汇总一下几个常用的对话框类,省的需要的时候到处去找。

        所谓对话框类:就是要在Windows窗体(.NET 6.x以上)上使用的对话框类。虽然这些类的知识点是在.NET里定义的,但这些类同样适用于.NET Framework全系列。

        System.Windows.Forms 命名空间 | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms?view=windowsdesktop-8.0

        以下以.NET 8.0为例。

一、SaveFileDialog 类

        提示用户选择文件的保存位置。 此类不能被继承。

public sealed class SaveFileDialog : System.Windows.Forms.FileDialog

1.源码示例

// 演示如何创建 SaveFileDialog、设置成员、
// 使用 ShowDialog 方法调用对话框以及保存当前文件。
namespace _SaveFileDialog
{
    public partial class Form1 : Form
    {
        private readonly Button? button1;

        public Form1()
        {
            InitializeComponent();
            //按钮控件及事件
            button1 = new Button()
            {
                Location = new Point(167, 90),
                Name = "button1",
                Size = new Size(80, 23),
                Text = "存储",
                UseVisualStyleBackColor = true,
            };
            button1.Click += new EventHandler(Button1_Click);

            //Form1()
            ClientSize = new Size(265, 170);
            StartPosition = FormStartPosition.CenterScreen;
            Name = "Form1";
            Text = "SaveFileDialog_test";
            Controls.Add(button1);
            PerformLayout();
        }
        /// <summary>
        /// 向当前文件夹存储“文件名.txt”,手动输入文件名
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            Stream myStream;
            SaveFileDialog saveFileDialog1 = new()
            {
                Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    // Code to write the stream goes here.
                    myStream.Close();
                }
            }
        }
    }
}

2.生成效果

二、OpenFileDialog类

        显示一个标准对话框,提示用户打开文件。 此类不能被继承。

public sealed class OpenFileDialog : System.Windows.Forms.FileDialog

1.源码示例

//创建 一个 OpenFileDialog,设置多个属性来定义文件扩展名筛选器和对话框行为,
//并使用 CommonDialog.ShowDialog 方法显示对话框。
namespace _OpenFileDialog
{
    public partial class Form1 : Form
    {
        private readonly Button? button1;

        public Form1()
        {
            InitializeComponent();

            //按钮控件及事件
            button1 = new Button()
            {
                Location = new Point(167, 90),
                Name = "button1",
                Size = new Size(80, 23),
                Text = "打开文件",
                UseVisualStyleBackColor = true,
            };
            button1.Click += new EventHandler(Button1_Click);

            //Form1()
            ClientSize = new Size(265, 170);
            StartPosition = FormStartPosition.CenterScreen;
            Name = "Form1";
            Text = "OpenFileDialog_test";
            Controls.Add(button1);
            PerformLayout();
        }

        /// <summary>
        /// 按下按钮,浏览文件位置并打开文件
        /// 最后显示文件位置和文件内容
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            var fileContent = string.Empty;
            var filePath = string.Empty;

            using (OpenFileDialog openFileDialog = new())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Get the path of specified file
                    filePath = openFileDialog.FileName;

                    //Read the contents of the file into a stream
                    var fileStream = openFileDialog.OpenFile();

                    using StreamReader reader = new(fileStream);
                    fileContent = reader.ReadToEnd();
                }
            }

            MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
        }
    }
}

2.生成效果

 

三、ColorDialog类

        表示一个通用对话框,该对话框显示可用的颜色以及允许用户定义自定义颜色的控件。

public class ColorDialog : System.Windows.Forms.CommonDialog

1.示例源码

//创建新的 ColorDialog。从现有窗体中调用 方法。
namespace _ColorDialog
{
    public partial class Form1 : Form
    {
        private readonly TextBox? textBox1;
        private readonly Button? button1;

        public Form1()
        {
            InitializeComponent();
            //文本框控件
            textBox1 = new TextBox()
            {
                Location = new Point(81, 15),
                Name = "textBox1",
                Size = new Size(145, 21),
                Text = "",
            };

            //按钮控件及事件
            button1 = new Button()
            {
                Location = new Point(167, 90),
                Name = "button1",
                Size = new Size(80, 23),
                Text = "选择字体",
                UseVisualStyleBackColor = true,
            };
            button1.Click += new EventHandler(Button1_Click);

            //Form1()
            ClientSize = new Size(265, 170);
            StartPosition = FormStartPosition.CenterScreen;
            Name = "Form1";
            Text = "ColorDialog_test";
            Controls.Add(textBox1);
            Controls.Add(button1);
            PerformLayout();
        }
        /// <summary>
        /// 按钮事件:生成颜色对话框的新实例
        /// 文本框里的的文字的颜色=选定的颜色
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            ColorDialog MyDialog = new()
            {
                // Keeps the user from selecting a custom color.
                AllowFullOpen = false,
                // Allows the user to get help. (The default is false.)
                ShowHelp = true,
                // Sets the initial color select to the current text color.
                Color = textBox1!.ForeColor
            };

            // Update the text box color if the user clicks OK 
            if (MyDialog.ShowDialog() == DialogResult.OK)
                textBox1.ForeColor = MyDialog.Color;
        }
    }
}

2.生成效果

四、FontDialog类

        提示用户从本地计算机上安装的字体中选择一种字体。

public class FontDialog : System.Windows.Forms.CommonDialog

1.源码示例

//使用 ShowDialog 显示 FontDialog。
namespace _FontDialog
{
    public partial class Form1 : Form
    {
        private readonly TextBox? textBox1;
        private readonly Button? button1;
        private readonly FontDialog? fontDialog1;

        public Form1()
        {
            InitializeComponent();

            //文本框控件
            textBox1 = new TextBox()
            {
                Location = new Point(81, 15),
                Name = "textBox1",
                Size = new Size(145, 21),
                Text = "",
            };

            //fontDialog1 
            fontDialog1 = new FontDialog();

            //按钮控件及事件
            button1 = new Button()
            {
                Location = new Point(167, 90),
                Name = "button1",
                Size = new Size(80, 23),
                Text = "选择字体",
                UseVisualStyleBackColor = true,
            };
            button1.Click += new EventHandler(Button1_Click);

            //Form1()
            ClientSize = new Size(265, 170);
            StartPosition = FormStartPosition.CenterScreen;
            Name = "Form1";
            Text = "FontDialog_test";
            Controls.Add(textBox1);
            Controls.Add(button1);
            PerformLayout();
        }
        /// <summary>
        /// 按钮事件:
        /// 文本框里的的文字的字体字号=选定的字体字号
        /// </summary>
        private void Button1_Click(object? sender, EventArgs e)
        {
            fontDialog1!.ShowColor = true;

            //fontDialog1.Font = textBox1!.Font;
            //fontDialog1.Color = textBox1.ForeColor;

            if (fontDialog1.ShowDialog() != DialogResult.Cancel)
            {
                textBox1!.Font = fontDialog1.Font;
                textBox1!.ForeColor = fontDialog1.Color;
            }
        }
    }
}

2.生成效果

 

五、FolderBrowserDialog类

        提示用户选择文件夹。 此类不能被继承。

public sealed class FolderBrowserDialog : System.Windows.Forms.CommonDialog

1.示例源码

// 来源于:FolderBrowserDialog 类 (System.Windows.Forms) | Microsoft Learn
// https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.folderbrowserdialog?view=windowsdesktop-8.0
// 但微软搞错了,这个例子里的部分类只能运行于 .NET Framework 4.8
// 本例的环境VS2022 7.8.1,窗体应用, .NET Framework 4.8
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private readonly FolderBrowserDialog folderBrowserDialog1;
        private readonly OpenFileDialog openFileDialog1;

        private readonly RichTextBox richTextBox1;

        private readonly MainMenu mainMenu1;
        private readonly MenuItem fileMenuItem;
        private readonly MenuItem openMenuItem;
        private readonly MenuItem folderMenuItem;
        private readonly MenuItem closeMenuItem;
        public string openFileName;
        public string folderName;
        private bool fileOpened = false;

        // Constructor.
        public Form1()
        {
            InitializeComponent();

            mainMenu1 = new MainMenu();        // .NET Framework 4.8的类,.NET 7.0不支持,以下同
            fileMenuItem = new MenuItem();
            openMenuItem = new MenuItem();
            folderMenuItem = new MenuItem();
            closeMenuItem = new MenuItem();

            openFileDialog1 = new OpenFileDialog();
            folderBrowserDialog1 = new FolderBrowserDialog();
            richTextBox1 = new RichTextBox();

            mainMenu1.MenuItems.Add(fileMenuItem);
            fileMenuItem.MenuItems.AddRange(
                            new MenuItem[] {openMenuItem,
                                                                 closeMenuItem,
                                                                 folderMenuItem});
            fileMenuItem.Text = "File";

            openMenuItem.Text = "Open...";
            openMenuItem.Click += new EventHandler(OpenMenuItem_Click);

            folderMenuItem.Text = "Select Directory...";
            folderMenuItem.Click += new EventHandler(FolderMenuItem_Click);

            closeMenuItem.Text = "Close";
            closeMenuItem.Click += new EventHandler(CloseMenuItem_Click);
            closeMenuItem.Enabled = false;

            openFileDialog1.DefaultExt = "rtf";
            openFileDialog1.Filter = "rtf files (*.rtf)|*.rtf";

            // Set the help text description for the FolderBrowserDialog.
            folderBrowserDialog1.Description =
                "Select the directory that you want to use as the default.";

            // Do not allow the user to create new files via the FolderBrowserDialog.
            folderBrowserDialog1.ShowNewFolderButton = false;

            // Default to the My Documents folder.
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

            richTextBox1.AcceptsTab = true;
            richTextBox1.Location = new Point(8, 8);
            richTextBox1.Size = new Size(280, 344);
            richTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left |
                                       AnchorStyles.Bottom | AnchorStyles.Right;

            ClientSize = new Size(296, 360);
            Controls.Add(richTextBox1);
            Menu = mainMenu1;
            Text = "RTF Document Browser";
        }

        // Bring up a dialog to open a file.
        private void OpenMenuItem_Click(object sender, EventArgs e)
        {
            // If a file is not opened, then set the initial directory to the
            // FolderBrowserDialog.SelectedPath value.
            if (!fileOpened)
            {
                openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
                openFileDialog1.FileName = null;
            }

            // Display the openFile dialog.
            DialogResult result = openFileDialog1.ShowDialog();

            // OK button was pressed.
            if (result == DialogResult.OK)
            {
                openFileName = openFileDialog1.FileName;
                try
                {
                    // Output the requested file in richTextBox1.
                    Stream s = openFileDialog1.OpenFile();
                    richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
                    s.Close();

                    fileOpened = true;
                }
                catch (Exception exp)
                {
                    MessageBox.Show("An error occurred while attempting to load the file. The error is:"
                                    + System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
                    fileOpened = false;
                }
                Invalidate();

                closeMenuItem.Enabled = fileOpened;
            }

            // Cancel button was pressed.
            else if (result == DialogResult.Cancel)
            {
                return;
            }
        }

        // Close the current file.
        private void CloseMenuItem_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            fileOpened = false;

            closeMenuItem.Enabled = false;
        }

        // Bring up a dialog to chose a folder path in which to open or save a file.
        private void FolderMenuItem_Click(object sender, EventArgs e)
        {
            // Show the FolderBrowserDialog.
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                folderName = folderBrowserDialog1.SelectedPath;
                if (!fileOpened)
                {
                    // No file is opened, bring up openFileDialog in selected path.
                    openFileDialog1.InitialDirectory = folderName;
                    openFileDialog1.FileName = null;
                    openMenuItem.PerformClick();
                }
            }
        }
    }
}

2.生成效果

        生成的窗体,文件菜单,打开文件菜单并浏览文件位置,确定要打开的文件,浏览文件可设定默认打开的文件。

 

        思考:看过我连续的2篇总结,知道组件(控件)和类的差别了吗?

六、总结:组件(控件)和类的差别

        类更复杂并成一个体系,它包括:构造函数、属性、方法、事件、字段,等;而控件就简单多了,往往只有有限的属性和有限的事件;

        类是进化到高端的产品,它几乎都可以向下兼容;而控件是初期的产品,随着软件进化升级,其全部或部分因被其他功能替代而消失。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wenchm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值