ProjectItemsEvents | | How can I use the ProjectItemsEvents to get notification when an item is added to a VB or C# project, in an add-in? This is a problem that I struggled with in my early add-in days, and because I could not figure how to get the ProjectItemsEvents to work properly, I went around the world to figure out how to know when a Form or Class was added to the project.
Like many areas of extensibility in Visual Studio .NET, MSDN documentation is not very helpful on this particular topic. In this article, I will show you that it is very simple to do, once you see how it is done. I will illustrate through the description of some code taken directly from an add-in.
First, I will declare two events; one for trapping the addition of a VB Project Item and the other for a C# project.
Public Shared oVS As EnvDTE.DTE
Public WithEvents eventsPIVB As EnvDTE.ProjectItemsEvents
Public WithEvents eventsPICSharp As EnvDTE.ProjectItemsEvents
Dim events As EnvDTE.Events
|
Next, I will place code in the OnConnection event to sink the event handlers for the two events as follows:
' sink the event handlers for events
events = oVS.Events
eventsPIVB = oVS.Events.GetObject("VBProjectItemsEvents")
eventsPICSharp = oVS.Events.GetObject("CSharpProjectItemsEvents")
|
The object oVS is my shortened "applicationObject" name supplied to the OnConnection event by the IDE. Next, I will click on the object drop down list in the Code Window for and choose the WithEvents objects listed above. Obviously, I will choose one of them and then click on the right hand drop down list, which will have a list of three events. I will select the ItemAdded event because that is the one in which I am interested. When I clck on that event, the IDE will create an event handler for me. Next, I will select the other WithEvents object and repeat these steps to create the second event handler.
Finally, I will place a simple Debug.Writline call in each of the events as follows:
Private Sub eventsPIVB_ItemAdded(ByVal ProjectItem As EnvDTE.ProjectItem) _
Handles eventsPIVB.ItemAdded
Debug.Write("ProjectItemAdded: " & ProjectItem.Name)
End Sub
Private Sub eventsPICSharp_ItemAdded(ByVal ProjectItem As EnvDTE.ProjectItem) _
Handles eventsPICSharp.ItemAdded
Debug.Write("ProjectItemAdded: " & ProjectItem.Name)
End Sub
|
When I run the add-in the ItemAdded event will fire when I add a new Form or Class to the project. The event that will fire will be based on the language of the project, either VB or C#.
|