Tuesday, July 31, 2007

Adding a Recent menu to your application

An easy way to implement a Recent menu in your application is to use the My.Settings namespace and store the recently opened items in a StringCollection setting.

1. Create a setting called RecentDocuments of type System.Collections.Specialized.StringCollection.
2. Add the following methods to your form class:

Private Function GetRecentDocuments() As StringCollection
'StringCollection can be stored in XML - it's easier than maintaining five
'separate strings
in the settings collection, because the StringCollection
'can be manipulated all at once

If My.Settings.RecentDocuments Is Nothing Then
My.Settings.RecentDocuments = New StringCollection()
End If
Return My.Settings.RecentDocuments
End Function

Private Sub AddRecentDocument(ByVal strPath As String)
GetRecentDocuments()
If My.Settings.RecentDocuments.Contains(strPath) Then
'If this document was already in the recent list, move it to the top and
'slide everything else down

My.Settings.RecentDocuments.Remove(strPath)
ElseIf My.Settings.RecentDocuments.Count = 5 Then
'If the recent document list is full, drop the last one
My.Settings.RecentDocuments.RemoveAt(4)
End If
My.Settings.RecentDocuments.Insert(0, strPath)
End Sub

3. Add a Recent menu somewhere on your form (I usually make this a submenu under File).
4. In the Form.Load event, call GetRecentDocuments() and iterate through the strings, creating submenu items for the Recent menu.

Dim intI As Integer = 1
For Each strPath As String In GetRecentDocuments()
Dim tmi As New ToolStripMenuItem("&" + CStr(intI) + " - " + strPath)
RecentToolStripMenuItem.DropDownItems.Add(tmi)
intI += 1
Next


5. When an item is opened, pass the appropriate string to AddRecentDocument() and rebuild the Recent menu based on the new StringCollection.

No comments: