views:

56

answers:

1

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  A: 

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.

Hans Passant
Can I get the currently running instance instead of starting a new one?
JoelFan
@Joel: What if there are two or more VS instances - how would the above VBScript choose?
Simon Chadwick
@Joel: you can't, you can only create a new instance. Standard COM server practice. Some servers publish a class factory in the ROT, Visual Studio doesn't.
Hans Passant
You can. See [here](http://social.msdn.microsoft.com/Forums/en/vsxprerelease/thread/3e2db97c-1b71-4d3f-b58b-a27089e84446) for a starting point. If there are multiple instances of VS open, then the running object table will contain multiple objects with monikers that contain "VisualStudio.DTE.10.0".
Noah Richards
@Noah: sounds good! Not quite cut-and-paste code though.
Hans Passant
Another option... put the code in a Visual Studio add-in
JoelFan
Yes, good idea.
Hans Passant