May 4, 2011

How to store/restore UI state of Visual Studio tool window pane


A tool window pane of Visual Studio is a class that inherits from Microsoft.VisualStudio.Shell.ToolWindowPane. We can create a sub classes of this to add custom a tool window pane to our VSPackage.

ToolWindowPane class has overridable SaveUIState and LoadUIState methods. It seems that we can use them to store/restore UI state of tool window pane, but thier methods are never called. According to this thread, it looks like their methods are only called on document windows not tool window panes.

Instead of SaveUIState and LoadUIState, we can use OnCreate and OnClose methods. Just like the name implies, OnCreate is called when a tool window pane is created, and OnClose is called when a tool window pane is closed. So if we override them, we can implement the feature to store/restore UI state.

For example, we can store UI state to xml file and restore UI state from xml file like this.

public CustomToolWindowPane : ToolWindowPane
{
    private string path;

    public CustomToolWindowPane()
    {
        ...
        var directory = Path.GetDirectoryName(typeof(CustomToolWindowPane).Assembly.Location);
        path = Path.Combine(directory, "uistate.xml");
    }

    protected override void OnCreate()
    {
        using (var stream = File.Open(path, FileMode.Open))
        {
            var serializer = new XmlSerializer(typeof(UIState));
            var state = (UIState)serializer.Deserialize(stream);
            ApplyUIState(state);
        }
    }

    private void ApplyUIState(UIState state)
    {
        ...
    }

    protected override void OnClose()
    {
        var state = BuildUpUIState();
        using (var stream = File.Open(path, FileMode.Create))
        {
            var serializer = new XmlSerializer(typeof(UIState));
            serializer.Serialize(stream, state);
        }
    }

    private UIState BuildUpUIState()
    {
        ...
    }


    public class UIState
    {
        ...
    }
}

No comments:

Post a Comment