Search code examples
c#visual-studiopluginssyntax-highlightingvsix

Getting theme colors in Visual Studio Classifier extension


I'm building a syntax highlighting extension for the Properties language in Visual Studio and already built the classifier/tagger. I'm stuck however at setting/choosing the right colors for the different tags (i.e. keys, values, comments).

I'd like to make the colors follow the current theme of Visual Studio. Right now they're hard-coded (see ForegroundColor = ...):

[Export(typeof(EditorFormatDefinition))]
[ClassificationType(ClassificationTypeNames = "PropertiesKeyTypeDefinition")]
[Name("PropertiesKeyFormat")]
[Order(Before = Priority.Default)]
internal sealed class PropertiesKey : ClassificationFormatDefinition {
    public PropertiesKey() {
        DisplayName = "Properties Key";
        ForegroundColor = Color.FromRgb(86, 156, 214);
    }
}

What I've found so far:

If possible, I'd like to use the colors used for 'Keyword', 'String' and 'Comment' colors which can be found in VS in Tools -> Options -> Environment -> Fonts and Colors, again, in accordance with the current theme.


Solution

  • Based on the EnvironmentColors you can get a ThemeResourceKey.

    That key can than be transformed into a SolidColorBrush using this function:

    private static SolidColorBrush ToBrush(ThemeResourceKey key)
    {
        var color = VSColorTheme.GetThemedColor(key);
        return new SolidColorBrush(Color.FromArgb(color.A, color.R, color.G, color.B));
    }
    

    So assigning it to your foreground becomes:

    [Export(typeof(EditorFormatDefinition))]
    [ClassificationType(ClassificationTypeNames = "PropertiesKeyTypeDefinition")]
    [Name("PropertiesKeyFormat")]
    [Order(Before = Priority.Default)]
    internal sealed class PropertiesKey : ClassificationFormatDefinition {
        public PropertiesKey() {
            DisplayName = "Properties Key";
            ForegroundColor = ToBrush(EnvironmentColors.ClassDesignerCommentTextColorKey);
        }
     }
    

    Documentation:

    ThemeResouceKey

    VSColorTheme.GetThemedColor

    Extra:

    This might be helpful in selecting the right ThemeResourceKey

    VS Colors