C# VSTO:突出显示电子邮件正文文本 - ClearHitHighlight() 未清除?

C# VSTO: Highlighting E-mail Body Text - ClearHitHighlight() not clearing?

使用 VSTO 和 C#,我试图让 Outlook 突出显示电子邮件正文中的特定单词。到目前为止,我已经能够使用以下代码完成此操作:

       Outlook.MailItem mailItem = this.inspector.CurrentItem as Outlook.MailItem;

       if (inspector.IsWordMail())
       {
           var outlookWordDocument = inspector.WordEditor as Word.Document;
           if (outlookWordDocument == null || outlookWordDocument.Application.Selection == null)
           { return; }

           var wordRange = outlookWordDocument.Application.Selection.Range;

           Word.Find find_highlight = wordRange.Find;
           find_highlight.HitHighlight("apples", Word.WdColor.wdColorDarkRed);
           find_highlight.ClearHitHighlight(); // trying to clear for testing purposes, but does nothing
       }

我的问题是 ClearHitHighlight() 函数没有清除任何内容。我可以清除的唯一方法是我是否立即执行另一个搜索。请参阅下面的评论:

find_highlight.HitHighlight("apples"); //highlights "apples"
find_highlight.HitHighlight("oranges"); //highlights "oranges" too
find_highlight.ClearHitHighlight(); //does nothing
find_highlight.HitHighlight("pears"); //clears previous highlights, adds pears

作为替代方案,我可以通过格式化电子邮件的实际正文来突出显示文本,但是这个 HitHighlight 函数似乎更合适——如果我能弄清楚如何在完成后清除标记就好了!

如有任何帮助,我们将不胜感激。

不要对单词范围调用查找,而是对文档的内容变量调用查找。不确定确切原因,但此更改会导致正确的行为。

改变这个:

var wordRange = outlookWordDocument.Application.Selection.Range;

Word.Find find_highlight = wordRange.Find;

为此:

Word.Find find_highlight = outlookWordDocument.Content.Find;