你需要创建一个sink对于这些事件。
实施_dispVBProjectsEvents
调度接口 - 这是一个通过调用常规托管 .net 事件来响应这些事件的实现,有效地“包装”VBProjects
events:
public class VBProjectsEventsSink : _dispVBProjectsEvents
{
public event EventHandler<DispatcherEventArgs<VBProject>> ProjectAdded;
public void ItemAdded(VBProject VBProject)
{
if (VBProject.Protection == vbext_ProjectProtection.vbext_pp_none)
{
OnDispatch(ProjectAdded, VBProject);
}
}
public event EventHandler<DispatcherEventArgs<VBProject>> ProjectRemoved;
public void ItemRemoved(VBProject VBProject)
{
if (VBProject.Protection == vbext_ProjectProtection.vbext_pp_none)
{
OnDispatch(ProjectRemoved, VBProject);
}
}
public event EventHandler<DispatcherRenamedEventArgs<VBProject>> ProjectRenamed;
public void ItemRenamed(VBProject VBProject, string OldName)
{
var handler = ProjectRenamed;
if (handler != null && VBProject.Protection == vbext_ProjectProtection.vbext_pp_none)
{
handler.Invoke(this, new DispatcherRenamedEventArgs<VBProject>(VBProject, OldName));
}
}
public event EventHandler<DispatcherEventArgs<VBProject>> ProjectActivated;
public void ItemActivated(VBProject VBProject)
{
if (VBProject.Protection == vbext_ProjectProtection.vbext_pp_none)
{
OnDispatch(ProjectActivated, VBProject);
}
}
private void OnDispatch(EventHandler<DispatcherEventArgs<VBProject>> dispatched, VBProject project)
{
var handler = dispatched;
if (handler != null)
{
handler.Invoke(this, new DispatcherEventArgs<VBProject>(project));
}
}
}
The DispatcherEventArgs
类只是公开的一种便捷方式VBProject
与事件相关的项目,并且它可以重用于其他接收器:
public class DispatcherEventArgs<T> : EventArgs
where T : class
{
private readonly T _item;
public DispatcherEventArgs(T item)
{
_item = item;
}
public T Item { get { return _item; } }
}
客户端代码需要注册接收器 - 为此,您需要保留一个IConnectionPoint
场及其int
cookie:
private readonly IConnectionPoint _projectsEventsConnectionPoint;
private readonly int _projectsEventsCookie;
The VBProjects
集合实现了IConnectionPointContainer
接口,您需要使用它找到连接点:
var sink = new VBProjectsEventsSink();
var connectionPointContainer = (IConnectionPointContainer)_vbe.VBProjects;
var interfaceId = typeof (_dispVBProjectsEvents).GUID;
connectionPointContainer.FindConnectionPoint(ref interfaceId, out _projectsEventsConnectionPoint);
一旦你拥有了IConnectionPoint
, 使用Advise
方法“连接”您的接收器并检索cookie:
_projectsEventsConnectionPoint.Advise(sink, out _projectsEventsCookie);
然后您可以像处理任何“正常”.net 事件一样处理接收器事件:
sink.ProjectAdded += sink_ProjectAdded;
sink.ProjectRemoved += sink_ProjectRemoved;
sink.ProjectActivated += sink_ProjectActivated;
sink.ProjectRenamed += sink_ProjectRenamed;
当你想断开你的水槽时,你可以通过cookie to the Unadvise
的方法IConnectionPoint
实例:
_projectsEventsConnectionPoint.Unadvise(_projectsEventsCookie);
“就那么简单!”