There are several possibilities. I will explain one using
Application Settings.
First, in the
solution explorer, right-click on your project, then choose
properties, and select the
Settings tab.
In the
Name column, enter
Mru
In the
Type column, select
System.Collections.Specialized.StringCollection
In the
Scope column, select
User
In the
Value column, click on the small button to edit the collection, enter any value, then click on OK, then click again on the button, remove the value and click OK again to make the collection empty. Without this trick, the collection wouldn't be instanciated and you would have an exception will running your code.
OK you have created your MRU list and it will be saved in your application settings file.
Now let's add some code in your form. I suppose you already created a menu with two entries:
Open
and
Recent files
.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
UpdateMRUMenu();
recentFilesToolStripMenuItem.DropDownItemClicked += new ToolStripItemClickedEventHandler(recentFilesToolStripMenuItem_DropDownItemClicked);
}
void recentFilesToolStripMenuItem_DropDownItemClicked(object sender,
ToolStripItemClickedEventArgs e)
{
OpenFile(e.ClickedItem.Text);
}
private void UpdateMRUMenu()
{
recentFilesToolStripMenuItem.DropDownItems.Clear();
foreach (string path in Properties.Settings.Default.Mru)
recentFilesToolStripMenuItem.DropDownItems.Add(path);
}
void AddToMRU(string path)
{
Properties.Settings.Default.Mru.Insert(0, path);
while (Properties.Settings.Default.Mru.Count > 5)
Properties.Settings.Default.Mru.RemoveAt(Properties.Settings.Default.Mru.Count - 1);
Properties.Settings.Default.Save();
UpdateMRUMenu();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
string path = dlg.FileName;
AddToMRU(path);
OpenFile(path);
}
}
void OpenFile(string path)
{
...
}
}