I'm sitting here writing some macros to help test a new feature I've implemented in the debugger. Doing so is always an interesting experience. There is quite a lot of functionality available via automation, but it isn't always straightforward how to access it. It makes me wonder how many people use macros and automation, especially with the debugger.
Many things are very easy. To load the solution, I just call:
DTE.Solution.Open(“MyApp.sln”)
To start debugging, it just takes:
DTE.Debugger.Go()
But then to figure out how to set the caret in the document is not so intuitive.
It's pretty easy to figure out that DTE.ActiveDocument.Selection gives the selection, but statement completion doesn't provide any methods or properties to set the selection. I finally figured out that you have to assign the selection to a TextSelection object. This has a MoveToPoint method, which takes a TextPoint. However, I can't just create a “New TextPoint()”. It took some more time to realize that you can't create these from scratch, but have to create them from an existing EditPoint. Here's my final solution:
Private Sub SetCaretPosition(ByVal Line As Integer, ByVal Column As Integer)
Try
If Not DTE.ActiveDocument Is Nothing Then
Dim selection As TextSelection = DTE.ActiveDocument.Selection
Dim point As EnvDTE.EditPoint = selection.ActivePoint.CreateEditPoint()
point.MoveToLineAndOffset(Line, Column)
selection.MoveToPoint(point)
End If
Catch ex As System.Exception
TestOutput("Unable to set caret position. " + ex.ToString)
End Try
End Sub
Now after moving the caret, I can change the current statement by calling DTE.ExecuteStatement(“Debug.SetNextStatement“). Mission accomplished.