Search code examples
c#.netvbavisio

MSVisio Characters custom color


I know, that I can change color of all text in shape this way:

Shape.CellsU["Char.Color"].FormulaForceU = "RGB(255,255,255)";

There is also way to change color of certain characters in shape this way:

Characters.Begin = 2;
Characters.End = 5;    
Characters.set_CharProps((short)MSVisio.VisCellIndices.visCharacterColor, (short)MSVisio.VisDefaultColors.visRed;);

But I can't find any way to pass custom RGB (or HEX or any type) value of color to just certain characters in shape. I don't want to cut shape into little shapes.

Can you please help? Thanks


Solution

  • The CharProps property allows you to set an index into the predefined document colors collection. For a custom RGB you can set the corresponding cell formula by first getting the row index with CharPropsRow like this:

        var shp = vApp.ActiveWindow.Selection.PrimaryItem;
        var shpChars = shp.Characters;
    
        shpChars.Begin = 2;
        shpChars.End = 5;
        //shpChars.set_CharProps((short)Visio.VisCellIndices.visCharacterColor, (short)Visio.VisDefaultColors.visRed);
    
        var targetRow = shpChars.CharPropsRow[0];
        shp.CellsSRC[(short)Visio.VisSectionIndices.visSectionCharacter, 
                     targetRow,
                     (short)Visio.VisCellIndices.visCharacterColor].FormulaU = "RGB(40,220,40)";
    

    and that should give you similar results to this: enter image description here

    [Update] The above assumes you're targeting existing formating and changing it. To add new runs you can use CharProps first to add the row and then the CharPropsRow to target that new run. So you can run this code against a new page:

        var vPag = vApp.ActivePage;
        var shp = vPag.DrawRectangle(3,3,5,4);
        shp.Text = "GoodMorning";
    
        var shpChars = shp.Characters;
    
        shpChars.Begin = 0;
        shpChars.End = 4;
        var targetRow = shpChars.CharPropsRow[(short)Visio.VisCharsBias.visBiasLetVisioChoose];
        shp.CellsSRC[(short)Visio.VisSectionIndices.visSectionCharacter,
                     targetRow,
                     (short)Visio.VisCellIndices.visCharacterColor].FormulaU = "RGB(220,40,40)";
    
        shpChars.Begin = 4;
        shpChars.End = 11;
        shpChars.set_CharProps((short)Visio.VisCellIndices.visCharacterColor, (short)Visio.VisDefaultColors.visBlack);
        targetRow = shpChars.CharPropsRow[(short)Visio.VisCharsBias.visBiasLetVisioChoose];
        shp.CellsSRC[(short)Visio.VisSectionIndices.visSectionCharacter,
                     targetRow,
                     (short)Visio.VisCellIndices.visCharacterColor].FormulaU = "RGB(40,200,40)";
    

    ...and this should result in the following:

    enter image description here