注:要建立一个带历史信息的菜单,将主窗体设置为父窗体。并将在菜单中最近打开文件的文件名和路径保存到事先建立的*.ini文件中。

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace MenuHistory1
{
    public partial class frmMenuHistory : Form
    {
        string adress;
        public frmMenuHistory()
        {
            InitializeComponent();

            //获取或设置当前工作目录的完全限定路径

            adress = System.Environment.CurrentDirectory;        

        }

        /// <summary>
        /// 将打开的文件路径写入INI文件       

        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmiOpen_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            StreamWriter sw = new StreamWriter(adress + "\\
menu.ini", true);
            sw.WriteLine(openFileDialog1.FileName); //写入INI文件
            sw.Flush();
            sw.Close();
            ShowWindows(openFileDialog1.FileName);
        }

        /// <summary>
        /// 读取INI文件并将信息加入菜单的实现代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMenuHistory_Load(object sender, EventArgs e)
        {
            StreamReader sr = new StreamReader(adress + "\\menu.ini"
);
            int i = this.tsmiFile.DropDownItems.Count - 2;
            while (sr.Peek() > 0)
            {
                ToolStripMenuItem menuitem = new ToolStripMenuItem(sr.ReadLine());
                this.tsmiFile.DropDownItems.Insert(i, menuitem);
                i++;
                menuitem.Click += new EventHandler(menuitem_Click); //表示将处理不包含事件数据的事件的方法
            }
        }

        private void menuitem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = (ToolStripMenuItem)sender;
            ShowWindows(menu.Text);
        }

        /// <summary>
        /// 用来加载背景图片并显示窗体的自定义方法。
        /// </summary>
        /// <param name="fileName"></param>
        private void ShowWindows(string fileName)
        {
            Image pic = Image.FromFile(fileName);
            Form f = new Form();
            f.MdiParent = this;
            f.BackgroundImage = pic;
            f.Show();
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }
}