Thursday, February 10, 2005

Find a file in Solution Explorer [updated]

Solution explorer keeps jumping around every time you get latest. Refreshing the tree takes almost as long as getting the files. So.. turn off the syncronisation. Get latest now works faster.

Sometimes you want to find the current file in the tree though, so...

Here is a macro to find the active file in solution explorer.
[updated for vs2005 with changes from Simon R.]
Sub FindFileInSolutionExplorer()
Dim sln As String = DTE.Solution.FullName
sln = sln.Substring(sln.LastIndexOf("\") + 1)
sln = sln.Substring(0, sln.Length - 4)
Dim pi As Object = DTE.ActiveDocument.ProjectItem
Dim endString As String = "Microsoft Visual Studio"

Dim path As String
While (Not endString = pi.Name)
path = "\" & pi.Name() & path
pi = pi.Collection.Parent
End Whilejavascript:void(0)
path = sln & path

Dim UIH As UIHierarchy =
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Object
Dim anItem As UIHierarchyItem = UIH.GetItem(path)
anItem.Select(vsUISelectionType.vsUISelectionTypeSelect)
End Sub
Coupled with the ever useful "Collapse all the open project folders in the Solution Explorer".
Sub HideAllProjects()
DTE.SuppressUI = True

Dim UIH As UIHierarchy =
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Object
Dim aSoltion As UIHierarchyItem = UIH.UIHierarchyItems.Item(1)
Dim aProject As UIHierarchyItem

For Each aProject In aSoltion.UIHierarchyItems
Dim aFolder As UIHierarchyItem
For Each aFolder In aProject.UIHierarchyItems
aFolder.Collection.Expanded = False
Next
Next
DTE.SuppressUI = False
End Sub
I map these to
[Ctrl]+, = Collapse all
[Ctrl]+. = Select currently active file

Very handy.

6 comments:

L D said...

Excellent. Thanks for posting

Anonymous said...

Should this work under VS2005? I get an error "Public member 'Collection' on type 'DTE' not found". Any suggestions?

Nigel said...

Nope, they changed the marco API between 2003 and 2005. The macro should be something similar though.

If you get it working please post back here with the new version.

This should help http://msdn2.microsoft.com/en-us/library/aa300825(VS.71).aspx


Thanks, Nigel

Simon R. said...

FIXED!!

To fix, change the "Microsoft Development Environment" string to "Microsoft Visual Studio".

Thanks for the script :)

Simon R. said...

I also changed this line:
Dim sln As String = DTE.Solution.Item(1).Name

To this:
Dim sln As String = DTE.Solution.FullName
sln = sln.Substring(sln.LastIndexOf("\") + 1)
sln = sln.Substring(0, sln.Length - 4)

(This picks the solution name out of the .sln filepath)

Nigel said...

Thanks Simon.. I'll update the script.

GitHub Projects