如何处理保存事件 - C#

How to handle On Save Event - C#

我正在创建一个 .vsix(插件)项目来访问 VS 编辑器数据或文本。我能够在调试控制台中看到编辑器的文本,但现在我想要在保存文档时显示所有文本。我该如何处理 on saved event?

我尝试了以下代码但没有成功。

public void FormEvents_Save(object sender, SaveEventArgs<ITextView> e)
{
   MessageBox.Show("Saved!!");
}

我该如何处理on saved event

要检测文档保存事件( OnBeforeSave() 或 OnAfterSave() ),您可以实现 IVsRunningDocTableEvents3 接口。您可以通过将此接口实现到助手 class 中并公开一个 public 事件 event OnBeforeSaveHandler BeforeSave 和一个 public 委托 delegate void OnBeforeSaveHandler(object sender, Document document) 来做到这一点。

要捕获此事件:runningDocTableEvents.BeforeSave += OnBeforeSave 然后您可以在 OnBeforeSave 方法中编写代码。

当VS的任何一种保存命令(CTRL + S,全部保存,编译,构建等)被触发时,我都使用这个实现来格式化文档的代码样式。

我对 IVsRunningDocTableEvents3 接口的实现如下所示:

public class RunningDocTableEvents : IVsRunningDocTableEvents3
{
  #region Members

  private RunningDocumentTable mRunningDocumentTable;
  private DTE mDte;

  public delegate void OnBeforeSaveHandler(object sender, Document document);
  public event OnBeforeSaveHandler BeforeSave;

  #endregion

  #region Constructor

  public RunningDocTableEvents(Package aPackage)
  {
    mDte = (DTE)Package.GetGlobalService(typeof(DTE));
    mRunningDocumentTable = new RunningDocumentTable(aPackage);
    mRunningDocumentTable.Advise(this);
  }

  #endregion

  #region IVsRunningDocTableEvents3 implementation

  public int OnAfterAttributeChange(uint docCookie, uint grfAttribs)
  {
    return VSConstants.S_OK;
  }

  public int OnAfterAttributeChangeEx(uint docCookie, uint grfAttribs, IVsHierarchy pHierOld, uint itemidOld, string pszMkDocumentOld, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew)
  {
    return VSConstants.S_OK;
  }

  public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame)
  {
    return VSConstants.S_OK;
  }

  public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
  {
    return VSConstants.S_OK;
  }

  public int OnAfterSave(uint docCookie)
  {
    return VSConstants.S_OK;
  }

  public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame)
  {
    return VSConstants.S_OK;
  }

  public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining)
  {
    return VSConstants.S_OK;
  }

  public int OnBeforeSave(uint docCookie)
  {
    if (null == BeforeSave)
      return VSConstants.S_OK;

    var document = FindDocumentByCookie(docCookie);
    if (null == document)
      return VSConstants.S_OK;

    BeforeSave(this, FindDocumentByCookie(docCookie));
    return VSConstants.S_OK;
  }

  #endregion

  #region Private Methods

  private Document FindDocumentByCookie(uint docCookie)
  {
    var documentInfo = mRunningDocumentTable.GetDocumentInfo(docCookie);
    return mDte.Documents.Cast<Document>().FirstOrDefault(doc => doc.FullName == documentInfo.Moniker);
  }

  #endregion
}