Search code examples
pythonvisual-studiocom

Automate a running Visual Studio instance using COM to start debugging


How do I use COM automation to "Start Debugging" and "Toggle Breakpoint" in Microsoft Visual Studio Community 2022 (64-bit) Version 17.3.6?

enter image description here

enter image description here

I'm not sure what I need to call. I tried oleview.exe to find out the api, but have no clue how to use it.

Error handling omitted in this code:

import win32com.client as win32

gotoFile = "c:\\SomeFile.cpp"
gotoLine = 123
gotoChar = 12

breakpointFile = "c:\\SomeFile.cpp"
breakpointLine = 23

app = win32.GetActiveObject('VisualStudio.DTE')

app.MainWindow.Activate
app.MainWindow.Visible = True
app.UserControl = True

app.ItemOperations.OpenFile(gotoFile)
app.ActiveDocument.Selection.MoveToLineAndOffset(gotoLine, gotoChar)


app.{Toggle breakpoint in breakpointFile on breakpointLine (F9)} # How?
app.{Start Debugging (F5)} # How?

Solution

  • Since all the operations you need to execute are defined in VS as named commands, you can use the DTE.ExecuteCommand method:

    app.ExecuteCommand("Debug.ToggleBreakpoint")
    app.ExecuteCommand("Debug.Start")
    

    You can easily find all VS commands in the Tools > Options > Environment > Keyboard. Just start typing the required text, such as "start" in the "Show commands containing" field. You'll get the relevant commands.