Search code examples
c#vstopowerpointpowerpoint-addins

C# PowerPoint VSTO Addin: Change superscript font style after added text in PowerPoint TextRange


In one of my C# PowerPoint VSTO Addins, I have added some text in superscript at the current cursor location in a shape's TextRange like this

PowerPoint.TextRange superscriptText = Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange.InsertAfter("xyz");
superscriptText.Font.Superscript = Office.MsoTriState.msoCTrue;

This works as intended: the string "xyz" is inserted in superscript at the current cursor location. The problem is that once "xyz" is inserted, the font style is still in superscript for all text that follows i.e., text that the user types at the cursor after inserting the "xyz". How can I change the tex style at the cursor back to being non-superscripted after inserting superscripted text? I have unsuccessfully tried with

Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange.Font.Superscript = Office.MsoTriState.msoFalse;

But further typed text still continues in superscript.


Solution

  • Two possibilities:

    1. You can, work with the InsertAfter (and InsertBefore) methods in combination with the required formatting.

    The formatting is appended to the InsertAfter method:

    PowerPoint.TextRange superscriptText = Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange;
    superscriptText.InsertAfter("xyz").Font.Superscript = Office.MsoTriState.msoCTrue;
    superscriptText.InsertAfter(" not superscript").Font.Superscript = Office.MsoTriState.msoCFalse;
    
    1. Create a second TextRange object when using InsertAfter. The language reference states:

    Appends a string to the end of the specified text range. Returns a TextRange object that represents the appended text.

    Create a new TextRange and format it separately

    PowerPoint.TextRange superscriptText = Globals.ThisAddIn.Application.ActiveWindow.Selection.TextRange;
    superscriptText.InsertAfter("xyz")
    superscriptText.Font.Superscript = Office.MsoTriState.msoCTrue;
    PowerPoint.TextRange normalText = superscriptText.InsertAfter(" not superscript")
    normalText.Font.Superscript = Office.MsoTriState.msoCFalse;