Best Macro to use in Visual Studio

I wrote this little macro awhile back, and after getting burned by yet another accidental hit of the F1 key and waiting the agonizing amount of time before the Help came up, I realized it's time to get this macro out there so I can "install" it wherever I'm at. Since whenever I’m looking up documentation on a .NET class I copy the class name, go to Google, and generally the answer is within the first couple links. So why not automate that.

To add it to your Visual Studio macros, bring up the Macro Explorer panel (View –> Other Windows –> Macro Explorer; or Alt + F8). Edit a module and add sub to the module you want to.

Public Sub SearchWord()
Dim objDocument As EnvDTE.Document = DTE.ActiveDocument
Dim sSearchText As String

Dim currentSelection As TextSelection = objDocument.Selection

If currentSelection.Text <> "" Then
sSearchText = currentSelection.Text
Dim objTextDocument As EnvDTE.TextDocument
Dim objTextSelection As EnvDTE.TextSelection
Dim lineNumber As Integer
Dim colNumber As Integer

' Get the text document
objTextDocument = CType(objDocument.Object, EnvDTE.TextDocument)
objTextSelection = objTextDocument.Selection
colNumber = objTextSelection.ActivePoint.DisplayColumn
lineNumber = objTextSelection.ActivePoint.Line

objTextSelection.WordLeft(False, 1)
objTextSelection.WordRight(True, 1)

sSearchText = objTextSelection.Text
objTextSelection.MoveToDisplayColumn(lineNumber, colNumber)
End If

System.Diagnostics.Process.Start("http://www.google.com/search?q=" + sSearchText)
End Sub

Save the module and you can close out of the Macro editor. Now back in Visual Studio, open up the keyboard options (Tools –> Options –> Environment –> Keyboard). Remove the existing F1 binding by searching for “Help.F1Help” in the “Show commands containing” textbox and clicking the Remove button to unbind it. Now search for the macro you just created. Press the F1 key in the “Press shortcut keys” textbox and click “Assign”.

Now whenever you hit F1 it will highlight the current word and search for it in Google in your default browser. Pretty simple stuff!

EDIT (2010-01-18): Based on feedback I updated the macro to not change the selected text if there's already something selected, and won't leave an item selected if you didn't have something selected already.

Post a Comment