How can I AutoSave my Visual Studio 2015 files when it loses focus?

二次信任 提交于 2019-11-28 21:23:32

You can use the following extension for Visual Commander to auto save files on switching away from Visual Studio:

public class E : VisualCommanderExt.IExtension
{
    public void SetSite(EnvDTE80.DTE2 DTE_, Microsoft.VisualStudio.Shell.Package package)
    {
        DTE = DTE_;
        System.Windows.Application.Current.Deactivated += OnDeactivated;
    }

    public void Close()
    {
        System.Windows.Application.Current.Deactivated -= OnDeactivated;
    }

    private void OnDeactivated(object sender, System.EventArgs e)
    {
        try
        {
            DTE.ExecuteCommand("File.SaveAll");
        }
        catch (System.Exception ex)
        {
        }
    }

    private EnvDTE80.DTE2 DTE;
}

The solution above with

DTE.ExecuteCommand("File.SaveAll");

is too slow in case of 1000+ projects in solution, MSVS UI hangs for several seconds on each losing focus event and extremely consumes CPU, even if there are no unsaved changes.

I've edited OnDeactivated() method, and it works much faster in my cases:

private void OnDeactivated(object sender, System.EventArgs e)
{
    try
    {
        EnvDTE.Documents docs = DTE.Documents;

        for (int i = 1; i <= docs.Count; i++) {
            EnvDTE.Document doc = docs.Item(i);
            if (!doc.Saved) {
                doc.Save();
            }
        }
    }
    catch (System.Exception ex)
    {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!