Every once in a while I get mail asking how to find what is selected within the class view window. For a while I was telling everybody who asked that it was not possible because there is not an automation model on the class view window. But recently I stumbled across a way of finding out what is selected through another part of the object model. This works for C# and VC projects, but not for VB or J# (we will see why in a minute).

When an item is selected in the class view tool window, and the project that item is contained within is a C# or VC project, either the code model element or the Project object for that item is placed into the properties window. Since a System.Object/IDispatch can be retrieved for what is displayed within the properties window with the DTE.SelectedItems.SelectionContainer property, you can write code such as shown in the following macro to inspect the selected item to find out more information about what is selected:

    Sub classwindow()

        Dim cc As CodeClass

        Dim cn As CodeNamespace

        Dim cp As CodeProperty

        Dim cf As CodeAttribute

        Dim proj As Project

        Dim obj As Object

        obj = DTE.SelectedItems.SelectionContainer.Item(1)

        Try

            proj = obj

        Catch ex1 As System.Exception

            Try

                cc = obj

            Catch ex2 As System.Exception

                Try

                    cn = obj

                Catch ex3 As System.Exception

                    Try

                        cf = obj

                    Catch ex4 As System.Exception

                        Try

                            cp = obj

                        Catch ex5 As System.Exception

                            MsgBox("Unknown type")

                        End Try

                    End Try

                End Try

            End Try

        End Try

    End Sub

As I said, this only works for C# and VC projects, but not VB or J# ones. Why? Because those two languages don’t push an item into the class view window, and without that item in the properties window, there is nothing to retrieve.