要检测文档保存事件( OnBeforeSave() 或 OnAfterSave() ),您可以实现IVsRunningDocTableEvents3 接口。您可以通过将此接口实现到帮助程序类中并公开公共事件event OnBeforeSaveHandler BeforeSave 和公共委托delegate void OnBeforeSaveHandler(object sender, Document document) 来做到这一点。
要捕获此事件:runningDocTableEvents.BeforeSave += OnBeforeSave,然后您可以在 OnBeforeSave 方法中编写代码。
当任何来自 VS 的保存命令(CTRL + S、Save All、Compile、Build 等)被触发时,我已使用此实现来格式化文档的代码样式。
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
}