0
votes

I'm trying to add a rich text content control around the user's selected text in a Word document.

I'm new to VSTO and Content Controls so i'm using the MSDN examples as a baseline. The example shows this, which adds the Content Control at the chosen position:

private void AddRichTextControlAtSelection()
        {
            word.Document currentDocument = Globals.ThisAddIn.Application.ActiveDocument;

            currentDocument.Paragraphs[1].Range.InsertParagraphBefore();
            currentDocument.Paragraphs[1].Range.Select();

            Document extendedDocument = Globals.Factory.GetVstoObject(currentDocument);

            richTextControl1 = extendedDocument.Controls.AddRichTextContentControl("richTextControl1");
            richTextControl1.PlaceholderText = "Enter your first name";
        }

However i want the Content Control to wrap around the user's selected text. Any help, please?

2
Simple fix in the end: currentDocument.ActiveWindow.Selection.Range.Select();Can'tCodeWon'tCode
if you answered your own question, please post your Answer and accept it.user1379931

2 Answers

0
votes

Simple fix in the end: currentDocument.ActiveWindow.Selection.Range.Select();

0
votes

What you found is one possibility. More efficient and "cleaner" (IMO) would be to use the constructor that accepts a RANGE object and pass the Range. If you want the user's selection then

richTextControl1 = extendedDocument.Controls.AddRichTextContentControl(extendedDocument.Parent.Selection.Range, "richTextControl1");
//the Parent of a Document is the Word.Application
//Selection is a dependent of the Word.Application

Otherwise, building on your code sample:

richTextControl1 = extendedDocument.Controls.AddRichTextContentControl(currentDocument.Paragraphs[1].Range, "richTextControl1");

Note that if you don't need to work with VSTO's extensions of the Content Controls you don't need to go through the GlobalFactory steps, you can simply insert the "interop" versions of the Content Controls.