
Adding Bookmark Controls at Run Time in an Application-Level Project
Starting in SP1, you can add Bookmark controls programmatically to any open document at run time by using an application-level add-in. To do this, generate a Document host item that is based on an open document, and then use methods of the Controls property of this host item. There are two method overloads that you can use to add a Bookmark control in the following ways:
Dynamically created Bookmark controls are not persisted in the document when the document is closed. However, a native Microsoft.Office.Interop.Word..::.Bookmark remains in the document. You can recreate a Bookmark that is based on a native bookmark the next time the document is opened. For more information, see Persisting Dynamic Controls in Office Documents.
For more information about generating host items in application-level projects, see Extending Word Documents and Excel Workbooks in Application-Level Add-ins at Run Time.
To add a Bookmark control at a specified range
Use the ControlCollection..::.AddBookmark(Range, String) method, and pass in the Range where you want to add the Bookmark.
The following code example adds a new Bookmark to the beginning of the active document. To use this example, run the code from the ThisAddIn_Startup event handler in a Word add-in project.
Dim extendedDocument As Document = Me.Application.ActiveDocument.GetVstoObject()
Dim firstParagraph As Bookmark = extendedDocument.Controls.AddBookmark( _
extendedDocument.Paragraphs(1).Range, "FirstParagraph")
Document extendedDocument = this.Application.ActiveDocument.GetVstoObject();
Bookmark firstParagraph = extendedDocument.Controls.AddBookmark(
extendedDocument.Paragraphs[1].Range, "FirstParagraph");
To add a Bookmark control that is based on a native Bookmark control
Use the ControlCollection..::.AddBookmark(Bookmark, String) method, and pass in the existing Microsoft.Office.Interop.Word..::.Bookmark that you want to use as the basis for the new Bookmark.
The following code example creates a new Bookmark that is based on the first Microsoft.Office.Interop.Word..::.Bookmark in the active document. To use this example, run the code from the ThisAddIn_Startup event handler in a Word add-in project.
If Me.Application.ActiveDocument.Bookmarks.Count > 0 Then
Dim firstBookmark As Word.Bookmark = Me.Application.ActiveDocument.Bookmarks(1)
Dim extendedDocument As Document = Me.Application.ActiveDocument.GetVstoObject()
Dim vstoBookmark As Bookmark = extendedDocument.Controls.AddBookmark( _
firstBookmark, "VSTOBookmark")
End If
if (this.Application.ActiveDocument.Bookmarks.Count > 0)
{
object index = 1;
Word.Bookmark firstBookmark = this.Application.ActiveDocument.Bookmarks.get_Item(ref index);
Document extendedDocument = this.Application.ActiveDocument.GetVstoObject();
Bookmark vstoBookmark = extendedDocument.Controls.AddBookmark(
firstBookmark, "VSTOBookmark");
}