我正在创建一个.vsix(插件)项目,用于访问VS Editor数据或文本。我可以在调试控制台中看到编辑器的文本,但是现在我希望保存文档时显示所有文本。如何处理on saved event
?
我尝试了以下代码,但是没有用。
public void FormEvents_Save(object sender, SaveEventArgs<ITextView> e)
{
MessageBox.Show("Saved!!");
}
我该如何处理on saved event
?
要检测文档保存事件(OnBeforeSave()或OnAfterSave()),您可以实现IVsRunningDocTableEvents3
接口。您可以通过在助手类中实现此接口并公开一个公共事件event OnBeforeSaveHandler BeforeSave
和一个公共委托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
}