How to change a ClassificationFormatDefinition

纵然是瞬间 提交于 2020-07-08 00:59:22

问题


My Visual Studio extension (VSIX) is derived from the Ook Language Example (found here). Basically, I have the following ClassificationFormatDefinition with a function loadSavedColor that loads the color the user has configured. Everything works fine.

[Name("some_unique_name")]
internal sealed class OokE : ClassificationFormatDefinition
{
    public OokE()
    {
        DisplayName = "ook!"; //human readable version of the name
        ForegroundColor = loadSavedColor();
    }
}

Question: After the user has configured a new color, I like to invalidate the existing instance of class OokE or change the existing instances and set ForegroundColor. But whatever I do the syntax color is not updated.

I've tried:

  1. Get a reference to class OokE and update ForegroundColor.
  2. Invalidate the corresponding ClassificationTypeDefinition:

    [Export(typeof(ClassificationTypeDefinition))] [Name("ook!")] internal static ClassificationTypeDefinition ookExclamation = null;


回答1:


After hours of sifting through code I could create something that works. The following method UpdateFont called with colorKeyName equal to "some_unique_name" does the trick. I hope it is useful for someone.

private void UpdateFont(string colorKeyName, Color c)
{
    var guid2 = Guid.Parse("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}");
    var flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES;
    var store = GetService(typeof(SVsFontAndColorStorage)) as IVsFontAndColorStorage;

    if (store.OpenCategory(ref guid2, (uint)flags) != VSConstants.S_OK) return;
    store.SetItem(colorKeyName, new[]{ new ColorableItemInfo
        {
            bForegroundValid = 1,
            crForeground = (uint)ColorTranslator.ToWin32(c)
        }});
    store.CloseCategory();
}

After setting the new color, you will need to clear the cache with the following code:

IVsFontAndColorCacheManager cacheManager = this.GetService(typeof(SVsFontAndColorCacheManager)) as IVsFontAndColorCacheManager;
cacheManager.ClearAllCaches();
var guid = new Guid("00000000-0000-0000-0000-000000000000");
cacheManager.RefreshCache(ref guid);
guid = new Guid("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}"); // Text editor category


来源:https://stackoverflow.com/questions/47956223/how-to-change-a-classificationformatdefinition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!