
384
|
Chapter 12, Extending Visual Studio
#86 Automate Visual Studio
HACK
If Not d Is active Then
d.Close( )
End If
Next
End Sub
Another way to work with a document is to manipulate its actual text. Many
of the macros in this book do this. To work with the text of the document,
you will use the
TextSelection object. The TextSelection object is a refer-
ence to the currently selected text, but it can really be used to change any of
the text in the document.
The
TextSelection object contains methods like StartOfDocument, EndOf-
Document
, StartOfLine, and EndOfLine. Something I commonly have to do is
move existing text into a try...catch block—this is something you could
easily automate using the
TextSelection object. Here is an example of a
macro that surrounds the selected text with a
Try...Catch block:
Public Sub InsertTryCatch( )
Dim selection As TextSelection = ActiveDocument.Selection
Dim text As String
text = "try" & vbCrLf & " { " & vbCrLf & _
selection.Text & vbCrLf & "}" & vbCrLf & _
"catch" & vbCrLf & "{" & vbCrLf & "}"
selection.Text = text
End Sub
You would need to write a different macro to create a VB.NET Try...Catch
block.
The
Documents object is extremely valuable. When writing macros and add-
ins, this will probably be one of the more frequent objects you use.
Invoke Commands
The DTE object includes a Commands collection that contains all of the com-
mands currently in Visual Studio. Commands ...