Search code examples
ms-wordvstooffice-interopoffice-addins

How to emphasise text in Word, without alter the document, like in Grammarly


I am writing a VSTO add-inn to Word (and Outlook as well). I want to emphasize certain parts of the text (detected errors). As far as I know, there is no API for this kind of emphasizing in Microsoft.Office.Interop.Word or other libraries.

But Grammarly (www.grammarly.com) has found a way to do it:

Screendump from Word with Grammarly running

Does anyone know how you can do it the same way?


Solution

  • I believe that the best way to do this would be to place the desired text into a Range and then apply the following formatting:

    myRange.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineThick;
    myRange.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
    

    How This Would Work With Grammerly

    As previously pointed out in the comments for the question, the only way to add the emphasis is to change the document temporarily, which is what Grammerly seems to do in a very smart way. Grammerly only works when one clicks the Open Grammerly button on the Grammerly ribbon. If you do a simple experiment, you may be able to observe how Grammerly controls its temporary changes.

    First create an unsaved document with some misspelled words that show the wavy red line. Then click the Open Grammerly button. Notice that the add-in turns off spell checking and replaces it with its own web-triggered markings that are generated in the document and similar to what is generated by the code above. Then save the document. If you look carefully, you will see a small blink wherein the red thick underlines disappear for a brief moment. That is the Document.BeforeSave event removing their markings before saving the document. By relying on user actions, Grammerly controls at what points in time the markings appear. It then uses code and events to make sure the markings are not saved with the document or interfere with other operations.

    Some of the events you may want to look at are the:

    Document.BeforeSave Event

    Document.BeforePrint Event

    Document.BeforeClose Event