簡體   English   中英

VSTO Word加載項-在所選文本周圍插入內容控件

[英]VSTO Word Add-in - insert Content Control around selected text

我正在嘗試在Word文檔中圍繞用戶選擇的文本添加富文本內容控件。

我是VSTO和Content Control的新手,所以我使用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();

您發現的是一種可能性。 更有效和更“干凈”(IMO)的方法是使用接受RANGE對象並傳遞Range的構造函數。 如果要用戶選擇,則

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步驟,則只需插入“互操作”版本的內容控件即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM