如何使用VS Package on File Save Event为VS2012创建扩展

时间:2014-02-14 10:14:01

标签: visual-studio-2012 visual-studio-addins visual-studio-extensions vspackage

我需要在visual studio中的File Save Event上创建一个扩展来执行一些自定义活动。如何使用VS Package实现这一目标。

我对以下代码感到震惊,有什么建议吗?

    #region Package Members

    FileEventsListener listener = null;

    protected override void Initialize()
    {
        Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
        base.Initialize();

        listener = new FileEventsListener();

    }

    #endregion
}

public class FileEventsListener : IPersistFileFormat, IDisposable
{
    private IVsSolution solution;
    private uint solutionEventsCookie;
    private bool isDirty;
    private string fileName;
    private const uint MyFormat = 0;
    private const string MyExtension = ".edmx";

    public FileEventsListener()
    {
        //solution = Package.GetGlobalService(typeof(SPersistFileFormat)) as IVsSolution;

        //if (solution != null)
        //{
        //    solution.AdviseSolutionEvents(this, out solutionEventsCookie);
        //}
    }

    #region IDisposable Members

    public void Dispose()
    {

    }

    #endregion

    public int GetClassID(out Guid pClassID)
    {
        ErrorHandler.ThrowOnFailure(((IPersist)this).GetClassID(out pClassID));
        return VSConstants.S_OK;
    }

    public int GetCurFile(out string ppszFilename, out uint pnFormatIndex)
    {
        pnFormatIndex = MyFormat;
        ppszFilename = fileName;
        return VSConstants.S_OK;
    }

    public int GetFormatList(out string ppszFormatList)
    {
        char Endline = (char)'\n';
        string FormatList = string.Format(CultureInfo.InvariantCulture, "My Editor (*{0}){1}*{0}{1}{1}", MyExtension, Endline);
        ppszFormatList = FormatList;
        return VSConstants.S_OK;
    }

    public int InitNew(uint nFormatIndex)
    {
        if (nFormatIndex != MyFormat)
        {
            return VSConstants.E_INVALIDARG;
        }
        // until someone change the file, we can consider it not dirty as
        // the user would be annoyed if we prompt him to save an empty file
        isDirty = false;
        return VSConstants.S_OK;
    }

    public int IsDirty(out int pfIsDirty)
    {
        pfIsDirty = 0;

        return VSConstants.S_OK;
    }

    public int Load(string pszFilename, uint grfMode, int fReadOnly)
    {
        fileName = pszFilename;
        return VSConstants.S_OK;
    }

    public int Save(string pszFilename, int fRemember, uint nFormatIndex)
    {
        return VSConstants.S_OK;
    }

    public int SaveCompleted(string pszFilename)
    {
        return VSConstants.S_OK;
    }
}

}

1 个答案:

答案 0 :(得分:2)

您可以订阅DTE.Events.DocumentEvents.DocumentSaved活动。