2010-06-17 30 views
2

我为MS Word创建了一个AddIn。有一个新标签和一个按钮。我添加了一个新的模板文档,其中包含一个RichTextContentControl。访问RichTextContentControl使用C的MS Word中的AddIn文本#

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);    

我想获得的RichTextContentControl内的文本。我如何在我的AddIn项目中访问RichTextContentControl的文本或内容?

string text = contentControl1.Range.Text; 

此外,有许多的方法可以通过内容控制迭代,并只选择特定类型或内容控制哪个匹配的内容控制:

回答

3

内容控制的文本可以如下访问某个标签或标题。

这是因为你可能要处理符合特定类型或命名惯例,只有内容的控制非常重要,请参见下面的例子:

 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); 
      } 
     }