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)
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

ElseIf My.Settings.RecentDocuments.Count = 5 Then
'If the recent document list is full, drop the last one
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)
intI += 1

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

MDI Application Quick Start

Here's what needs to happen to get an MDI application up and running:

1. Set the form's IsMdiContainer property to True.
2. Create a menu strip for the form.
3. Create a Window menu in the menu strip.
4. Set the menu strip's MdiWindowListItem property to the name of the Window menu.

Always refer to the topmost window with a reference to the main form's ActiveMdiChild property.

When a new child window is created, set its MdiParent property to the main form.

Friday, July 13, 2007

Error inserting images into Word document

On calls to Range.InlineShapes.Add("C:\blah.jpg") and Range.Shapes.Add("C:\blah.jpg") I kept getting a very helpful, precise error:

The server threw an exception.
(Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))

Thanks for that!

After playing around with the code for awhile, I found that my particular problem was being caused by how I instantiated the Word.Document object. My code read:

Dim mobjWordApp As New Word.Application()
mobjWordApp.Visible = False
Dim objDocSet As Word.Documents = mobjWordApp.Documents
Dim objDoc As Word.Document = objDocSet.Add(Visible:=MsoTriState.msoFalse)

Removing the Visible parameter from the Documents.Add() call fixed the error. It was unnecessary anyway, since I had already set Application.Visible to False.