2010-06-17 61 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); 
      } 
     }