如何以编程方式突出显示Word文档中括号之间的单词

问题描述:

我试图突出显示Word文档中括号之间的文本,但是我的代码仅突出显示括号.这是我的代码:

I'm trying to highlight text between parentheses in a word document, but my code highlights only the parentheses. Here is my code:

private void button5_Click(object sender, EventArgs e)
{
    object textf = "(";
    object texs = ")";
    object color = Color.Cyan;
    object oMissing = System.Reflection.Missing.Value;
    acWord.Application.Selection.Find.ClearFormatting();

    acWord.Application.Selection.Find.HitHighlight(ref textf, ref color, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

} 

应该是这样的.

private void btnFind_Click(object sender, EventArgs e)
{
    object fileName = "xxxxx"; //The filepath goes here
    string textToFind = "xxxxx"; //The text to find goes here
    Word.Application word = new Word.Application();
    Word.Document doc = new Word.Document();
    object missing = System.Type.Missing;
    try
    {
        doc = word.Documents.Open(ref fileName, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing);
        doc.Activate();
        foreach (Word.Range docRange in doc.Words)
        {
            if(docRange.Text.Trim().Equals(textToFind,
               StringComparison.CurrentCultureIgnoreCase))
            {
                docRange.HighlightColorIndex = 
                  Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                docRange.Font.ColorIndex = 
                  Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message);
    }
}

您也可以尝试一下.

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordImage
{
    class ImageinWord
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Documents\WordDocuments\References.docx");

            TextSelection[] text = document.FindAllString("forming", false, true);
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("FindHighlight.docx");
        }
    }
}