开发者

Access RichTextContentControl Text from an AddIn in MS Word using C#

开发者 https://www.devze.com 2023-01-04 07:03 出处:网络
I\'ve created an AddIn for MS Word. There\'s a new tab and a button. I\'ve added a new template document that has a RichTextContentControl in it.

I've created an AddIn for MS Word. There's a new tab and a button. I've added a new template document that has a RichTextContentControl in it.

 WORD_APP = Globals.ThisAddIn.Application;
            object oMissing = System.Reflection.Missing.Value;开发者_高级运维
            object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
            oDoc = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);            

I want to get the text inside the RichTextContentControl. How can I access the text or content of a RichTextContentControl in my AddIn project?


The text of the content control can be accessed as follows:

string text = contentControl1.Range.Text;

Additionally, there are a number of ways you can iterate through content controls and only select content controls of specific type or content controls which match a certain tag or title.

This is quite important as you may want to process only content controls which match a specific type or naming convention, please see an example below:

        WORD_APP = Globals.ThisAddIn.Application;
        object oMissing = System.Reflection.Missing.Value;
        object oTemplate = "E:\\Sandbox\\TemplateWithFields\\TemplateWithFields\\TemplateWithFields.dotx";
        Word.Document document = WORD_APP.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);

        //Iterate through ALL content controls
        //Display text only if the content control is of type rich text
        foreach (Word.ContentControl contentControl in document.ContentControls)
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show(contentControl.Range.Text);
            }
        }

        //Only iterate through content controls where the tag is equal to "RT_Controls"
        foreach (Word.ContentControl contentControl in document.SelectContentControlsByTag("RT_Controls"))
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show("Selected by tag - " + contentControl.Range.Text);
            }
        }

        //Only iterate through content controls where the title is equal to "Title1"
        foreach (Word.ContentControl contentControl in document.SelectContentControlsByTitle("Title1"))
        {
            if (contentControl.Type == Word.WdContentControlType.wdContentControlRichText)
            {
                System.Windows.Forms.MessageBox.Show("Selected by title - " + contentControl.Range.Text);
            }
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消