Douglas
Douglas

Reputation: 54897

Highlight all occurrences of a string in Word using VSTO

I would like to highlight all occurrences of a given string in Microsoft Word 2010 using VSTO.

So far, I've managed to set the foreground color for the matches using the Find facility:

Word.Find find = Application.ActiveDocument.Content.Find;
find.Replacement.Font.ColorIndexBi = Word.WdColorIndex.wdYellow;
find.Execute(FindText: "dog", MatchCase: false, Replace: Word.WdReplace.wdReplaceAll);

However, I would like to set the highlight for the matches, such as in the screenshot below:

highlight word

Upvotes: 1

Views: 2152

Answers (2)

Douglas
Douglas

Reputation: 54897

If one wants temporary highlighting, one may use the HitHighlight method instead:

Word.Find find = Application.ActiveDocument.Content.Find;
find.HitHighlight(
    FindText: "dog",
    MatchCase: false,
    HighlightColor: Word.WdColor.wdYellow);

Upvotes: 3

user1379931
user1379931

Reputation:

Set the highlight colour by setting using

Application.Options.DefaultHighlightColorIndex 

to one of the wdColorIndex members (e.g. wdYellow)

Apply the Highlight colour in a Replace using

find.Replacement.Highlight = True

Upvotes: 2

Related Questions