VSTO Word 加载项 - 在所选文本周围插入内容控件
VSTO Word Add-in - insert Content Control around selected text
我正在尝试围绕用户在 Word 文档中选择的文本添加富文本内容控件。
我是 VSTO 和内容控件的新手,所以我使用 MSDN 示例作为基准。该示例显示了这一点,它在所选位置添加了内容控件:
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";
}
但是我希望内容控件环绕用户选择的文本。有什么帮助吗?
最后简单修复:currentDocument.ActiveWindow.Selection.Range.Select();
你发现的是一种可能。更有效和 "cleaner" (IMO) 将使用接受范围对象并传递范围的构造函数。如果你想要用户的选择那么
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
否则,基于您的代码示例构建:
richTextControl1 = extendedDocument.Controls.AddRichTextContentControl(currentDocument.Paragraphs[1].Range, "richTextControl1");
请注意,如果您不需要使用 VSTO 的内容控件扩展,则无需执行 GlobalFactory 步骤,只需插入 "interop" 版本的内容控件即可。
我正在尝试围绕用户在 Word 文档中选择的文本添加富文本内容控件。
我是 VSTO 和内容控件的新手,所以我使用 MSDN 示例作为基准。该示例显示了这一点,它在所选位置添加了内容控件:
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";
}
但是我希望内容控件环绕用户选择的文本。有什么帮助吗?
最后简单修复:currentDocument.ActiveWindow.Selection.Range.Select();
你发现的是一种可能。更有效和 "cleaner" (IMO) 将使用接受范围对象并传递范围的构造函数。如果你想要用户的选择那么
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
否则,基于您的代码示例构建:
richTextControl1 = extendedDocument.Controls.AddRichTextContentControl(currentDocument.Paragraphs[1].Range, "richTextControl1");
请注意,如果您不需要使用 VSTO 的内容控件扩展,则无需执行 GlobalFactory 步骤,只需插入 "interop" 版本的内容控件即可。