Getting theme colors in Visual Studio Classifier extension
Asked Answered
L

1

9

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.

Literati answered 20/8, 2016 at 11:38 Comment(0)
E
4

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

Elishaelision answered 19/2, 2019 at 10:58 Comment(1)
Note: I tried this and the correct theme color is selected only at the first start after installing the Visual Studio extension. Changing the theme afterwards does not adapt the color. Even restarting Visual Studio after changing the theme does not work. Only uninstalling the extension and then reinstalling seems to trigger Visual Studio to read the new color. Hence, this solution is fine if one wants to set the initial color based on an existing color the first time VS is started, and not support theme changes afterwards.Sandbank

© 2022 - 2024 — McMap. All rights reserved.