Automating Visual Studio 2010 from a console app

2019-08-29 03:13发布

I am trying to run the following code (which I got from here). The code just creates a new "Output" pane in Visual Studio and writes a few lines to it.

Public Sub WriteToMyNewPane()
    Dim win As Window = _
       dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
    Dim ow As OutputWindow = win.Object
    Dim owPane As OutputWindowPane
    Dim cnt As Integer = ow.OutputWindowPanes.Count
    owPane = ow.OutputWindowPanes.Add("My New Output Pane")
    owPane.Activate()
    owPane.OutputString("My text1" & vbCrLf)
    owPane.OutputString("My text2" & vbCrLf)
    owPane.OutputString("My text3" & vbCrLf)
End Sub

Instead of running it as a Macro, I want to run it as an independent console application that connects to a currently running instance of Visual Studio 2010. I'm having a hard time figuring out how to set the value of dte. I think I may need to call GetActiveObject, but I'm not sure how. Any pointers?

1条回答
做自己的国王
2楼-- · 2019-08-29 03:28

Yes, this is somewhat possible, the DTE interface supports out-of-process activation. Here's sample code that shows the approach:

Imports EnvDTE

Module Module1
    Sub Main()
        Dim dte As DTE = DirectCast(Interaction.CreateObject("VisualStudio.DTE.10.0"), EnvDTE.DTE)
        dte.SuppressUI = False
        dte.MainWindow.Visible = True
        Dim win As Window = dte.Windows.Item(Constants.vsWindowKindOutput)
        Dim ow As OutputWindow = DirectCast(win.Object, OutputWindow)
        Dim owPane As OutputWindowPane = ow.OutputWindowPanes.Add("My New Output Pane")
        owPane.Activate()
        owPane.OutputString("My text1" & vbCrLf)
        owPane.OutputString("My text2" & vbCrLf)
        owPane.OutputString("My text3" & vbCrLf)
        Console.WriteLine("Press enter to terminate visual studio")
        Console.ReadLine()
    End Sub
End Module

The previous to last statement shows why this isn't really practical. As soon as your program stops running, the last reference count on the coclass disappears, making Visual Studio quit.

查看更多
登录 后发表回答