Creating a Windows Form

VSTO does not use the same forms system used by VBA, so you need to re-create your VBA form using Windows Forms. Add a new Windows Form to the VSTO project by right-clicking the project, pointing to Add,

Figure 12.4. Using an existing document template

and then clicking Windows Form. In the Add New Item dialog box, name the form frmMain.vb. A new Windows form is added to your project, and the designer is opened.

You can now drag and drop controls onto your document to create a form that looks like your VBA UserForm. You can see in Figure 12.5 that the Windows Form is nearly identical.

You are now ready to populate the bookmarks when the user selects OK. Double-click the OK button on frmMain to create a Click event handler for the OK button. Type the code in Listing 12.3. You can see that it is almost identical to the VBA code. One difference is that you get a reference to the Document object in the With statement. In this case, because you are in a Windows Form you use the Globals object to reference the ThisDocument object. In addition, Visual Basic 2005 does not support default properties so you must specify the text property in all cases. You close the Windows Form using its Close method.

Figure 12.5. Creating a Windows Form

Listing 12.3. Populating bookmarks on an OK button Click event Public Class frmMain

Private Sub btnOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOK.Click

' Insert the fields into the bookmarks. With Globals.ThisDocument

.Bookmarks("To").Range.Text = txtTo.Text .Bookmarks("From").Range.Text = txtFrom.Text .Bookmarks("CC").Range.Text = txtCC.Text .Bookmarks("Re").Range.Text = txtRe.Text .Bookmarks("Subject").Range.Text = txtSubject.Text End With

' Close the form. Me.Close() End Sub End Class

0 0

Post a comment