C#中Windows窗体应用菜单设计.NET Framework 4.8 MainMenu类和MenuItem类 vs .NET 8.0 MenuStrip类和ToolStripMenuItem类

本文详细比较了.NETFramework4.8和8.0中MenuStrip类和ToolStripMenuItem类在Windows窗体应用中的区别和示例代码,包括菜单设计、功能展示和不同版本的适用性。

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

目录

 一、适用场合的不同

1.MainMenu类和MenuItem类

2.MenuStrip类和ToolStripMenuItem类

二、MainMenu类和MenuItem类用于.NET Framework 4.8 Windows窗体应用

三、MenuStrip类和ToolStripMenuItem类则用于 .NET 8.0 Windows窗体应用

1.示例源码

2.生成效果

四、MenuStrip类和ToolStripMenuItem类则用于 .NET 8.0 Windows窗体应用,不用设计器

1.示例源码 

2.生成效果

五、MenuStrip类和ToolStripMenuItem类则用于 .NET Framework4.8窗体应用,不用设计器

1.示例源码 

2.生成效果


 一、适用场合的不同

1.MainMenu类和MenuItem类

        MainMenu类和MenuItem类用于.NET Framework 4.8框架以下的Windows窗体应用菜单设计。

        MainMenu 类 (System.Windows.Forms) | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.mainmenu?view=netframework-4.8.1

        MenuItem 类 (System.Windows.Forms) | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.menuitem?view=netframework-4.8.1

 MainMenu类和MenuItem类适用于

产品

版本

.NET Framework

1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Windows Desktop

3.0

2.MenuStrip类和ToolStripMenuItem类

        MenuStrip类和ToolStripMenuItem类则用于 .NET 8.0 框架以下含.NET Framework 的Windows窗体应用菜单设计。 

        MenuStrip 类 (System.Windows.Forms) | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.menustrip?view=windowsdesktop-8.0

       ToolStripMenuItem 类 (System.Windows.Forms) | Microsoft Learn  https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.toolstripmenuitem?view=windowsdesktop-8.0

 MenuStrip类和ToolStripMenuItem类适用于

产品

版本

.NET Framework

2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

Windows Desktop

3.0, 3.1, 5, 6, 7, 8

二、MainMenu类和MenuItem类用于.NET Framework 4.8 Windows窗体应用

        示例参考作者文章:写文章-优快云创作中心  ,例五https://mp.youkuaiyun.com/mp_blog/creation/editor/134676994

        这两个类已被.NET抛弃,不建议再用。

三、MenuStrip类和ToolStripMenuItem类则用于 .NET 8.0 Windows窗体应用

1.示例源码

// Form1.cs
// Windows窗体应用.NET 8.0 
// MenuStrip和ToolStripMenuItem用法
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public string? openFileName;
        public string? folderName;
        public bool fileOpened = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripMenuItem1.Text = "文件";
            toolStripMenuItem2.Text = "打开";
            toolStripMenuItem3.Text = "关闭";
            toolStripMenuItem4.Text = "默认文件路径";
            ClientSize = new Size(296, 360);
            Controls.Add(richTextBox1);
            Controls.Add(menuStrip1);
            Text = "RTF Document Browser";

            openFileDialog1 = new OpenFileDialog     //默认打开文件扩展名
            {
                DefaultExt = "rtf",
                Filter = "rtf files (*.rtf)|*.rtf"
            };

            /// <summary>
            /// Set the help text description for the FolderBrowserDialog.
            /// Do not allow the user to create new files via the FolderBrowserDialog.
            /// Default to the My Documents folder.
            /// </summary>
            folderBrowserDialog1 = new FolderBrowserDialog
            {
                Description = "Select the directory that you want to use as the default.",
                ShowNewFolderButton = false,
                RootFolder = Environment.SpecialFolder.Personal
            };
        }

        /// <summary>
        /// If a file is not opened, then set the initial directory to the
        /// FolderBrowserDialog.SelectedPath value.
        /// </summary>
        #region 打开
        private void ToolStripMenuItem2_Click(object? sender, EventArgs e)
        {            
            if (!fileOpened)
            {
                openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
                openFileDialog1.FileName = null;
            }           
            DialogResult result = openFileDialog1.ShowDialog();  // Display the openFile dialog.
            if (result == DialogResult.OK)                       // OK button was pressed.
            {
                openFileName = openFileDialog1.FileName;
                try
                {                  
                    Stream s = openFileDialog1.OpenFile();       // Output the requested file in richTextBox1.
                    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:"
                                    + Environment.NewLine + exp.ToString() + Environment.NewLine);
                    fileOpened = false;
                }
                Invalidate();
                toolStripMenuItem3.Enabled = fileOpened;
            }
        }
        #endregion 打开

        #region 关闭
        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            fileOpened = false;
            toolStripMenuItem3.Enabled = false;
        }
        #endregion 关闭

        #region 选择文件
        private void ToolStripMenuItem4_Click(object sender, EventArgs e)
        {            
            DialogResult result = folderBrowserDialog1.ShowDialog();    // Show the FolderBrowserDialog.
            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;
                    toolStripMenuItem2.PerformClick();
                }
            }
        }
        #endregion 选择文件       
    }
}
//Form1.Designer.cs
namespace WinFormsApp1
{
    partial class Form1
    {      
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            richTextBox1 = new RichTextBox();
            menuStrip1 = new MenuStrip();
            toolStripMenuItem1 = new ToolStripMenuItem();
            toolStripMenuItem2 = new ToolStripMenuItem();
            toolStripMenuItem3 = new ToolStripMenuItem();
            toolStripMenuItem4 = new ToolStripMenuItem();
            folderBrowserDialog1 = new FolderBrowserDialog();
            openFileDialog1 = new OpenFileDialog();
            menuStrip1.SuspendLayout();
            SuspendLayout();
            // 
            // richTextBox1
            // 
            richTextBox1.Dock = DockStyle.Fill;
            richTextBox1.Location = new Point(0, 25);
            richTextBox1.Name = "richTextBox1";
            richTextBox1.Size = new Size(280, 296);
            richTextBox1.TabIndex = 0;
            richTextBox1.Text = "";
            // 
            // menuStrip1
            // 
            menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1 });
            menuStrip1.Location = new Point(0, 0);
            menuStrip1.Name = "menuStrip1";
            menuStrip1.Size = new Size(280, 25);
            menuStrip1.TabIndex = 1;
            menuStrip1.Text = "menuStrip1";
            // 
            // toolStripMenuItem1
            // 
            toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem2, toolStripMenuItem3, toolStripMenuItem4 });
            toolStripMenuItem1.Name = "toolStripMenuItem1";
            toolStripMenuItem1.Size = new Size(136, 21);
            toolStripMenuItem1.Text = "toolStripMenuItem1";
            // 
            // toolStripMenuItem2
            // 
            toolStripMenuItem2.Name = "toolStripMenuItem2";
            toolStripMenuItem2.Size = new Size(192, 22);
            toolStripMenuItem2.Text = "toolStripMenuItem2";
            toolStripMenuItem2.Click += ToolStripMenuItem2_Click;
            // 
            // toolStripMenuItem3
            // 
            toolStripMenuItem3.Name = "toolStripMenuItem3";
            toolStripMenuItem3.Size = new Size(192, 22);
            toolStripMenuItem3.Text = "toolStripMenuItem3";
            toolStripMenuItem3.Click += ToolStripMenuItem3_Click;
            // 
            // toolStripMenuItem4
            // 
            toolStripMenuItem4.Name = "toolStripMenuItem4";
            toolStripMenuItem4.Size = new Size(192, 22);
            toolStripMenuItem4.Text = "toolStripMenuItem4";
            toolStripMenuItem4.Click += ToolStripMenuItem4_Click;
            // 
            // openFileDialog1
            // 
            openFileDialog1.FileName = "openFileDialog1";
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(280, 321);
            Controls.Add(richTextBox1);
            Controls.Add(menuStrip1);
            MainMenuStrip = menuStrip1;
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "Form1";
            Load += Form1_Load;
            menuStrip1.ResumeLayout(false);
            menuStrip1.PerformLayout();
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private RichTextBox richTextBox1;
        private MenuStrip menuStrip1;
        private ToolStripMenuItem toolStripMenuItem1;
        private ToolStripMenuItem toolStripMenuItem2;
        private ToolStripMenuItem toolStripMenuItem3;
        private ToolStripMenuItem toolStripMenuItem4;
        private FolderBrowserDialog folderBrowserDialog1;
        private OpenFileDialog openFileDialog1;
    }
}

2.生成效果

        生成→ 文件菜单,打开,浏览文件夹并找到文件所在路径,本里rtf存放在当前文件夹内。打开文件,文本框显示文件内容。→如果,再,文件→ 关闭,则清空文本框;→如果,文件,默认文件路径,找到rtf文件所在,确认,则设置好了文件默认的打开路径。下次再打开,就默认打开默认文件路径。

 

四、MenuStrip类和ToolStripMenuItem类则用于 .NET 8.0 Windows窗体应用,不用设计器

1.示例源码 

// Form1.cs不用设计器
// Windows窗体应用.NET 8.0 
// MenuStrip和ToolStripMenuItem用法
using System.Windows.Forms;

namespace WinFormsApp2
{
    public partial class Form1 : Form
    {
        public string? openFileName;
        public string? folderName;
        public bool fileOpened = false;

        private RichTextBox? richTextBox1;
        private MenuStrip? menuStrip1;
        private ToolStripMenuItem? toolStripMenuItem1;
        private ToolStripMenuItem? toolStripMenuItem2;
        private ToolStripMenuItem? toolStripMenuItem3;
        private ToolStripMenuItem? toolStripMenuItem4;
        private FolderBrowserDialog? folderBrowserDialog1;
        private OpenFileDialog? openFileDialog1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        private void Form1_Load(object? sender, EventArgs e)
        {
            toolStripMenuItem1 = new ToolStripMenuItem();
            toolStripMenuItem1!.Text = "文件";            
            toolStripMenuItem2 = new ToolStripMenuItem();
            toolStripMenuItem2!.Text = "打开";
            toolStripMenuItem2.Click += ToolStripMenuItem2_Click;
            toolStripMenuItem3 = new ToolStripMenuItem();
            toolStripMenuItem3!.Text = "关闭";
            toolStripMenuItem3.Click += ToolStripMenuItem3_Click;
            toolStripMenuItem4 = new ToolStripMenuItem();
            toolStripMenuItem4!.Text = "默认文件路径";
            toolStripMenuItem4.Click += ToolStripMenuItem4_Click;
            toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem2, toolStripMenuItem3, toolStripMenuItem4 });

            menuStrip1 = new MenuStrip() 
            {
                Location = new Point(0, 0),
                Name = "menuStrip1",
                Size = new Size(280, 25),
                Text = "menuStrip1",               
             };
            menuStrip1?.ResumeLayout(false);
            menuStrip1?.PerformLayout();
            menuStrip1!.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1 });

            richTextBox1 = new RichTextBox
            {
                Dock = DockStyle.Fill,
                Location = new Point(0, 25),
                Name = "richTextBox1",
                Size = new Size(280, 296),
                Text = ""
            };

            openFileDialog1 = new OpenFileDialog     //默认打开文件扩展名
            {
                FileName = "openFileDialog1",
                DefaultExt = "rtf",
                Filter = "rtf files (*.rtf)|*.rtf"
            };

            /// <summary>
            /// Set the help text description for the FolderBrowserDialog.
            /// Do not allow the user to create new files via the FolderBrowserDialog.
            /// Default to the My Documents folder.
            /// </summary>
            folderBrowserDialog1 = new FolderBrowserDialog
            {
                Description = "Select the directory that you want to use as the default.",
                ShowNewFolderButton = false,
                RootFolder = Environment.SpecialFolder.Personal
            };

            MainMenuStrip = menuStrip1;
            menuStrip1.SuspendLayout();
            ClientSize = new Size(296, 360);
            Controls.Add(richTextBox1);
            Controls.Add(menuStrip1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "RTF Document Browser";
        }
        /// <summary>
        /// If a file is not opened, then set the initial directory to the
        /// FolderBrowserDialog.SelectedPath value.
        /// </summary>
        #region 打开
        private void ToolStripMenuItem2_Click(object? sender, EventArgs e)
        {
            if (!fileOpened)
            {
                openFileDialog1!.InitialDirectory = folderBrowserDialog1!.SelectedPath;
                openFileDialog1!.FileName = null;
            }
            DialogResult result = openFileDialog1!.ShowDialog();// Display the openFile dialog.
            if (result == DialogResult.OK)                      // OK button was pressed.
            {
                openFileName = openFileDialog1.FileName;
                try
                {
                    Stream s = openFileDialog1.OpenFile();      // Output the requested file in richTextBox1.
                    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:"
                                    + Environment.NewLine + exp.ToString() + Environment.NewLine);
                    fileOpened = false;
                }
                Invalidate();
                toolStripMenuItem3!.Enabled = fileOpened;
            }
        }
        #endregion 打开

        #region 关闭
        private void ToolStripMenuItem3_Click(object? sender, EventArgs e)
        {
            richTextBox1!.Text = "";
            fileOpened = false;
            toolStripMenuItem3!.Enabled = false;
        }
        #endregion 关闭

        #region 选择文件
        private void ToolStripMenuItem4_Click(object? sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1!.ShowDialog();
            // Show the FolderBrowserDialog.
            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;
                    toolStripMenuItem2!.PerformClick();
                }
            }
        }
        #endregion 选择文件 
    }
}

2.生成效果

         同例三。

五、MenuStrip类和ToolStripMenuItem类则用于 .NET Framework4.8窗体应用,不用设计器

1.示例源码 

// Form1.cs不用设计器
// Windows窗体应用.NET Framework 4.8 
// MenuStrip和ToolStripMenuItem用法
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public string openFileName;
        public string folderName;
        public bool fileOpened = false;

        private RichTextBox richTextBox1;
        private MenuStrip menuStrip1;
        private ToolStripMenuItem toolStripMenuItem1;
        private ToolStripMenuItem toolStripMenuItem2;
        private ToolStripMenuItem toolStripMenuItem3;
        private ToolStripMenuItem toolStripMenuItem4;
        private FolderBrowserDialog folderBrowserDialog1;
        private OpenFileDialog openFileDialog1;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripMenuItem1 = new ToolStripMenuItem
            {
                Text = "文件"
            };
            toolStripMenuItem2 = new ToolStripMenuItem
            {
                Text = "打开"
            };
            toolStripMenuItem2.Click += ToolStripMenuItem2_Click;
            toolStripMenuItem3 = new ToolStripMenuItem
            {
                Text = "关闭"
            };
            toolStripMenuItem3.Click += ToolStripMenuItem3_Click;
            toolStripMenuItem4 = new ToolStripMenuItem
            {
                Text = "默认文件路径"
            };
            toolStripMenuItem4.Click += ToolStripMenuItem4_Click;
            toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { toolStripMenuItem2, toolStripMenuItem3, toolStripMenuItem4 });

            menuStrip1 = new MenuStrip()
            {
                Location = new Point(0, 0),
                Name = "menuStrip1",
                Size = new Size(280, 25),
                Text = "menuStrip1",
            };
            menuStrip1?.ResumeLayout(false);
            menuStrip1?.PerformLayout();
            menuStrip1.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1 });

            richTextBox1 = new RichTextBox
            {
                Dock = DockStyle.Fill,
                Location = new Point(0, 25),
                Name = "richTextBox1",
                Size = new Size(280, 296),
                Text = ""
            };

            openFileDialog1 = new OpenFileDialog     //默认打开文件扩展名
            {
                FileName = "openFileDialog1",
                DefaultExt = "rtf",
                Filter = "rtf files (*.rtf)|*.rtf"
            };

            /// <summary>
            /// Set the help text description for the FolderBrowserDialog.
            /// Do not allow the user to create new files via the FolderBrowserDialog.
            /// Default to the My Documents folder.
            /// </summary>
            folderBrowserDialog1 = new FolderBrowserDialog
            {
                Description = "Select the directory that you want to use as the default.",
                ShowNewFolderButton = false,
                RootFolder = Environment.SpecialFolder.Personal
            };

            MainMenuStrip = menuStrip1;
            menuStrip1.SuspendLayout();
            ClientSize = new Size(296, 360);
            Controls.Add(richTextBox1);
            Controls.Add(menuStrip1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "RTF Document Browser";
        }

        /// <summary>
        /// If a file is not opened, then set the initial directory to the
        /// FolderBrowserDialog.SelectedPath value.
        /// </summary>
        #region 打开
        private void ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (!fileOpened)
            {
                openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
                openFileDialog1.FileName = null;
            }
            DialogResult result = openFileDialog1.ShowDialog();// Display the openFile dialog.
            if (result == DialogResult.OK)                     // OK button was pressed.
            {
                openFileName = openFileDialog1.FileName;
                try
                {
                    Stream s = openFileDialog1.OpenFile();              
                    // Output the requested file in richTextBox1.
                    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:"
                                    + Environment.NewLine + exp.ToString() + Environment.NewLine);
                    fileOpened = false;
                }
                Invalidate();
                toolStripMenuItem3.Enabled = fileOpened;
            }
        }
        #endregion 打开

        #region 关闭
        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            fileOpened = false;
            toolStripMenuItem3.Enabled = false;
        }
        #endregion 关闭

        #region 选择文件
        private void ToolStripMenuItem4_Click(object sender, EventArgs e)
        {
            DialogResult result = folderBrowserDialog1.ShowDialog();    
            // Show the FolderBrowserDialog.
            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;
                    toolStripMenuItem2.PerformClick();
                }
            }
        }
        #endregion 选择文件 
    }
}

2.生成效果

         同例三。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wenchm

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

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

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

打赏作者

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

抵扣说明:

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

余额充值