Following is a code sample of Addin I copied from MSDN(http://msdn.microsoft.com/en-us/library/vstudio/envdte.addin.aspx) and did some modifications to. I create a Add-in project by VS2008 and paste the following code into it.
But it seems that it does not work properly.
1> DTE Add-in count before and after the Update does not change
2> Guid of the added addin is all zeros
3> I get error: The parameter is incorrect, at code line: DTE.Solution.AddIns.Add
Public Sub OnConnection(ByVal application As Object, ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, ByRef custom As Array) Implements IDTExtensibility2.OnConnection
_applicationObject = CType(application, DTE2)
_addInInstance = CType(addInInst, AddIn)
Me.AddInExample(_applicationObject)
End Sub
Function BrowseFile() As String
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "*.dll file (*.dll)|*.dll|All files (*.*)|*.*"
OpenFileDialog1.FilterIndex = 1dialog
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
'MsgBox(OpenFileDialog1.FileName)
Return OpenFileDialog1.FileName
End If
Return ""
End Function
Sub AddInExample(ByVal DTE As DTE2)
' For this example to work correctly, there should be an add-in
' available in the Visual Studio environment.
' Set object references.
Dim addincoll As AddIns
Dim addinobj As AddIn
' Register an add-in, check DTE Add-in count before and after the
' Update.
addincoll = DTE.AddIns
MsgBox("AddIns collection parent name: " & addincoll.Parent.Name)
MsgBox("Number of Add-ins: " & addincoll.Count)
' NOTE: Use regsvr32 for Visual C++, regasm for [Visual Basic
' and Visual C#. Also, the pathname used below is an example only.
'Shell("regasm F:\AddIns\RegExplore\Debug\regexplore.dll")
'Shell("C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm e:\AddinTest1.dll")
Shell("C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm " & BrowseFile())
addincoll.Update()
MsgBox("Number of Add-ins: " & addincoll.Count)
addinobj = addincoll.Item(1)
' Connect the add-in if it is not already connected
' and list its SatelliteDLLPath and Guid.
If addinobj.Connected = False Then
addinobj.Connected = True
End If
MsgBox("Satellite DLL Path: " & addinobj.SatelliteDllPath)
MsgBox("DLL GUID: " & addinobj.Guid)
' Activates a solution add-in so that it is available, then
'deactivates it.
MsgBox(addinobj.ProgID)
MsgBox(addinobj.Description)
MsgBox(addinobj.Name)
addinobj = DTE.Solution.AddIns.Add(addinobj.ProgID, addinobj.Description, addinobj.Name, False)
DTE.Solution.AddIns.Item(1).Remove()
End Sub
I would start at the begining if I were you: MSDN VS Addin
Doing it this way allows you to debug (step-through) your code and will give you a good start. The page you are on assumes you already know how to do this.
Related
I am trying to get the current username in a Windows environment that uses Windows Authentication. The code exists in a class library that is built and referenced within a separate Visual Studio application:
Function GetUserName() As String
If TypeOf My.User.CurrentPrincipal Is
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function
I get an error when it's located in the class library. My.User.CurrentPrincipal comes back with {System.Security.Principal.GenericPrincipal} and My.User.Name is blank. When I put the exact same code into a brand new windows forms application it works - My.User.CurrentPrincipal comes back with {System.Security.Principal.WindowsPrincipal} and My.User.Name is the user's login name.
Microsoft documentation suggests that the My.User object will work in class libraries. Does anyone know why I'm getting different values when it's put into a class library and added as a .dll reference to a parent application?
The parent application is a class library that is an add-in for Microsoft PowerPoint. The code in the parent application that calls the above code (called UsageDataCollection.dll) is:
Public Class rbnOvaPowerPoint
Private DataCollector As UsageDataCollection.DataCollector
Private Sub butShare_Click(sender As Object, e As RibbonControlEventArgs) Handles butShare.Click
OtherTasks.CreateMailItem()
End Sub
End Class
And then in a separate module:
Module OtherTasks
Private DataCollector As New UsageDataCollection.DataCollector
Sub CreateMailItem()
Dim OutlookApp As Outlook._Application = CreateObject("Outlook.Application")
Dim mail As Outlook.MailItem = Nothing
Dim mailRecipients As Outlook.Recipients = Nothing
Dim mailRecipient As Outlook.Recipient = Nothing
DataCollector.UsageStatistics("CreateMailItem")
Try
mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem)
mail.Subject = "OvaPowerPoint"
mail.Body = "Check out OvaPowerPoint, a custom-built Arup add-in for PowerPoint!" & Strings.Chr(13) & Strings.Chr(13) & "About the Add-In:" & Strings.Chr(13) & "http://wiki.oasys.intranet.arup.com/X-Wiki/index.php/OvaPowerPoint" & Strings.Chr(13) & Strings.Chr(13) & "Installation File:" & Strings.Chr(13) & "\\n-ynas12\Software\Custom%20Applications\Plug-Ins\Microsoft%20PowerPoint\OvaPowerPoint\setup.exe"
mail.Display(True)
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message,
"An exception is occured in the code of add-in.")
Finally
If Not IsNothing(mailRecipient) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mailRecipient)
If Not IsNothing(mailRecipients) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mailRecipients)
If Not IsNothing(mail) Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mail)
End Try
End Sub
End Module
And the UsageStatistics subroutine in UsageDataCollection.dll looks like:
Imports System.IO
Imports System.Text
Public Class DataCollector
Public Sub UsageStatistics(myAction As String)
Dim myAssemblyName As String = System.Reflection.Assembly.GetCallingAssembly.GetName.Name
Dim myFilePath As String = "\\n-ywpress01\uploads\UsageData\" & myAssemblyName & ".csv"
Using LogFile As New StreamWriter(myFilePath, True)
LogFile.WriteLine("[" & DateTime.Now.ToUniversalTime.ToString("yyyy/MM/dd HH':'mm':'ss") & "]" & Chr(44) & GetUserName() & Chr(44) & GetUserLocation() & Chr(44) & myAction)
LogFile.Close()
End Using
End Sub
End Class
Thanks
Zak
In the MS docs, it says
For Windows applications, only projects built on the Windows Application template initialize the My.User object by default. In all other Windows project types, you must initialize the My.User object by calling the My.User.InitializeWithWindowsUser Method explicitly or by assigning a value to CurrentPrincipal.
The fix in your code is:
Function GetUserName() As String
My.User.InitializeWithWindowsUser() 'pulls the network credentials into .NET
If TypeOf My.User.CurrentPrincipal Is
Security.Principal.WindowsPrincipal Then
' The application is using Windows authentication.
' The name format is DOMAIN\USERNAME.
Dim parts() As String = Split(My.User.Name, "\")
Dim username As String = parts(1)
Return username
Else
' The application is using custom authentication.
Return My.User.Name
End If
End Function
I'm writing a screen capture application for a client. The capture part is fine, but he wants to get the name and path of the file that the capture is of.
Using system.diagnostics.process I am able to get the process that the capture is of, and can get the full path of the EXE, but not the file that is open.
ie. Notepad is open with 'TextFile1.txt' as its document. I can get from the process the MainWindowTitle which would be 'TextFile1.txt - Notepad' but what I need is more like 'c:\users....\TextFile1.txt'
Is there a way of getting more information from the process?
I'm sure there is a way, but I can't figure it out
Any help greatly appreciated.
You can use ManagementObjectSearcher to get the command line arguments for a process, and in this notepad example, you can parse out the file name. Here's a simple console app example that writes out the full path and file name of all open files in notepad..
Imports System
Imports System.ComponentModel
Imports System.Management
Module Module1
Sub Main()
Dim cl() As String
For Each p As Process In Process.GetProcessesByName("notepad")
Try
Using searcher As New ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " & p.Id)
For Each mgmtObj As ManagementObject In searcher.Get()
cl = mgmtObj.Item("CommandLine").ToString().Split("""")
Console.WriteLine(cl(cl.Length - 1))
Next
End Using
Catch ex As Win32Exception
'handle error
End Try
Next
System.Threading.Thread.Sleep(1000000)
End Sub
End Module
I had to add a reference to this specific dll:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Managment.dll
i think it is the simplest way
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "notepad" Then
ListBox1.Items.Add(prog.ProcessName)
End If
Next
I know this post is old, but since I've searched for this two days ago, I'm sure others would be interested. My code below will get you the file paths from Notepad, Wordpad, Excel, Microsoft Word, PowerPoint, Publisher, Inkscape, and any other text or graphic editor's process, as long as the filename and extension is in the title bar of the opened window.
Instead of searching, it obtains the file's target path from Windows' hidden Recent Items directory, which logs recently opened and saved files as shortcuts. I discovered this hidden directory in Windows 7. You're gonna have to check if Windows 10 or 11 has this:
C:\Users\ "username" \AppData\Roaming\Microsoft\Windows\Recent
I slapped this code together under Framework 4, running as 64bit. The COM dlls that must be referenced in order for the code to work are Microsoft Word 14.0 Object Library, Microsoft Excel 14.0 Object Library, Microsoft PowerPoint 14.0 Object Library, and Microsoft Shell Controls And Automation.
For testing, the code below needs a textbox, a listbox, a button, and 3 labels (Label1, FilenameLabel, Filepath).
Once you have this working, after submitting a process name, you will have to click the filename item in the ListBox to start the function to retrieve it's directory path.
Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop.Word
Imports Microsoft.Office.Interop.PowerPoint
Imports Shell32
Public Class Form1
'function gets names of all opened Excel workbooks, adding them to the ListBox
Public Shared Function ExcelProcess(ByVal strings As String) As String
Dim Excel As Microsoft.Office.Interop.Excel.Application = CType(Marshal.GetActiveObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
For Each Workbook As Microsoft.Office.Interop.Excel.Workbook In Excel.Workbooks
Form1.ListBox1.Items.Add(Workbook.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened Word documents, adding them to the ListBox
Public Shared Function WordProcess(ByVal strings As String) As String
Dim Word As Microsoft.Office.Interop.Word.Application = CType(Marshal.GetActiveObject("Word.Application"), Microsoft.Office.Interop.Word.Application)
For Each Document As Microsoft.Office.Interop.Word.Document In Word.Documents
Form1.ListBox1.Items.Add(Document.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened PowerPoint presentations, adding them to the ListBox
Public Shared Function PowerPointProcess(ByVal strings As String) As String
Dim PowerPoint As Microsoft.Office.Interop.PowerPoint.Application = CType(Marshal.GetActiveObject("PowerPoint.Application"), Microsoft.Office.Interop.PowerPoint.Application)
For Each Presentation As Microsoft.Office.Interop.PowerPoint.Presentation In PowerPoint.Presentations
Form1.ListBox1.Items.Add(Presentation.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'clears listbox to prepare for new process items
ListBox1.Items.Clear()
'gets process title from TextBox1
Dim ProcessName As String = TextBox1.Text
'prepare string's case format for
ProcessName = ProcessName.ToLower
'corrects Office process names
If ProcessName = "microsoft excel" Then
ProcessName = "excel"
Else
If ProcessName = "word" Or ProcessName = "microsoft word" Then
ProcessName = "winword"
Else
If ProcessName = "powerpoint" Or ProcessName = "microsoft powerpoint" Then
ProcessName = "powerpnt"
Else
End If
End If
End If
'get processes by name (finds only one instance of Excel or Microsoft Word)
Dim proclist() As Process = Process.GetProcessesByName(ProcessName)
'adds window titles of all processes to a ListBox
For Each prs As Process In proclist
If ProcessName = "excel" Then
'calls function to add all Excel process instances' workbook names to the ListBox
ExcelProcess(ProcessName)
Else
If ProcessName = "winword" Then
'calls function to add all Word process instances' document names to the ListBox
WordProcess(ProcessName)
Else
If ProcessName = "powerpnt" Then
'calls function to add all Word process instances' document names to the ListBox
PowerPointProcess(ProcessName)
Else
'adds all Notepad or Wordpad process instances' filenames
ListBox1.Items.Add(prs.MainWindowTitle)
End If
End If
End If
Next
End Sub
Private Sub ListBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick
Try
'add ListBox item (full window title) to string
Dim ListBoxSelection As String = String.Join(Environment.NewLine, ListBox1.SelectedItems.Cast(Of String).ToArray)
'get full process title after "-" from ListBoxSelection
Dim GetProcessTitle As String = ListBoxSelection.Split("-"c).Last()
'create string to remove from ListBoxSelection
Dim Remove As String = " - " & GetProcessTitle
'Extract filename from ListBoxSelection string, minus process full name
Dim Filename As String = ListBoxSelection.Substring(0, ListBoxSelection.Length - Remove.Length + 1)
'display filename
FilenameLabel.Text = "Filename: " & Filename
'for every file opened and saved via savefiledialogs and openfiledialogs in editing software
'Microsoft Windows always creates and modifies shortcuts of them in Recent Items directory:
'C:\Users\ "Username" \AppData\Roaming\Microsoft\Windows\Recent
'so the below function gets the target path from files's shortcuts Windows created
FilePathLabel.Text = "File Path: " & GetLnkTarget("C:\Users\" & Environment.UserName & "\AppData\Roaming\Microsoft\Windows\Recent\" & Filename & ".lnk")
Catch ex As Exception
'no file path to show if nothing was saved yet
FilePathLabel.Text = "File Path: Not saved yet."
End Try
End Sub
'gets file's shortcut's target path
Public Shared Function GetLnkTarget(ByVal lnkPath As String) As String
Dim shl = New Shell32.Shell()
lnkPath = System.IO.Path.GetFullPath(lnkPath)
Dim dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath))
Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
Return lnk.Target.Path
End Function
End Class
I'm building some Word 2003 macro that have to be put in the %APPDATA%\Microsoft\Word\Startup folder.
I can't change the location of this folder (to a network share). How can I auto update this macros ?
I have tried to create a bootstrapper macro, with an AutoExec sub that copy newer version from a file share to this folder. But as Word is locking the file, I get a Denied Exception.
Any idea ?
FYI, I wrote this code. The code is working fine for update templates in templates directory, but not in startup directory :
' Bootstrapper module
Option Explicit
Sub AutoExec()
Update
End Sub
Sub Update()
MirrorDirectory MyPath.MyAppTemplatesPath, MyPath.WordTemplatesPath
MirrorDirectory MyPath.MyAppStartupTemplatesPath, MyPath.WordTemplatesStartupPath
End Sub
' IOUtilities Module
Option Explicit
Dim fso As New Scripting.FileSystemObject
Public Sub MirrorDirectory(sourceDir As String, targetDir As String)
Dim result As FoundFiles
Dim s As Variant
sourceDir = RemoveTrailingBackslash(sourceDir)
targetDir = RemoveTrailingBackslash(targetDir)
With Application.FileSearch
.NewSearch
.FileType = MsoFileType.msoFileTypeAllFiles
.LookIn = sourceDir
.SearchSubFolders = True
.Execute
Set result = .FoundFiles
End With
For Each s In result
Dim relativePath As String
relativePath = Mid(s, Len(sourceDir) + 1)
Dim targetPath As String
targetPath = targetDir + relativePath
CopyIfNewer CStr(s), targetPath
Next s
End Sub
Public Function RemoveTrailingBackslash(s As String)
If Right(s, 1) = "\" Then
RemoveTrailingBackslash = Left(s, Len(s) - 1)
Else
RemoveTrailingBackslash = s
End If
End Function
Public Sub CopyIfNewer(source As String, target As String)
Dim shouldCopy As Boolean
shouldCopy = False
If Not fso.FileExists(target) Then
shouldCopy = True
ElseIf FileDateTime(source) > FileDateTime(target) Then
shouldCopy = True
End If
If (shouldCopy) Then
If Not fso.FolderExists(fso.GetParentFolderName(target)) Then fso.CreateFolder (fso.GetParentFolderName(target))
fso.CopyFile source, target, True
Debug.Print "File copied : " + source + " to " + target
Else
Debug.Print "File not copied : " + source + " to " + target
End If
End Sub
' MyPath module
Property Get WordTemplatesStartupPath()
WordTemplatesStartupPath = "Path To Application Data\Microsoft\Word\STARTUP"
End Property
Property Get WordTemplatesPath()
WordTemplatesPath = "Path To Application Data\Microsoft\Templates\Myapp\"
End Property
Property Get MyAppTemplatesPath()
MyAppTemplatesPath = "p:\MyShare\templates"
End Property
Property Get XRefStartupTemplatesPath()
MyAppStartupTemplatesPath = "p:\MyShare\startup"
End Property
[Edit] I explored another way
Another way I'm thinking about, is to pilot the organizer :
Sub Macro1()
'
' Macro1 Macro
' Macro recorded 10/7/2011 by beauge
'
Application.OrganizerCopy source:="P:\MyShare\Startup\myapp_bootstrapper.dot", _
Destination:= _
"PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot" _
, Name:="MyModule", Object:=wdOrganizerObjectProjectItems
End Sub
This is working, but has limitations :
either I have to hard-code modules to organize
or I have to change the option "Trust VBA project" to autodiscover items like this (which is not acceptable as it requires to lower the security of the station) :
the code of the project enumeration is this one :
Public Sub EnumProjectItem()
Dim sourceProject As Document
Dim targetProject As Document
Set sourceProject = Application.Documents.Open("P:\MyShare\Startup\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Set targetProject = Application.Documents.Open("PathToApplication Data\Microsoft\Word\STARTUP\myapp_bootstrapper.dot", , , , , , , , , wdOpenFormatTemplate)
Dim vbc As VBcomponent
For Each vbc In sourceProject.VBProject.VBComponents 'crash here
Application.ActiveDocument.Range.InsertAfter (vbc.Name + " / " + vbc.Type)
Application.ActiveDocument.Paragraphs.Add
Next vbc
End Sub
[Edit 2] Another unsuccessful try :
I put, in my network share, a .dot with all the logic.
In my STARTUP folder, I put a simple .Dot file, that references the former one, with a single "Call MyApp.MySub".
This is actually working, but as the target template is not in a trusted location, a security warning is popped up each time word is launched (even if not related to the current application macro)
At least, I succeed partially using these steps :
Create a setup package. I use a NSIS script
the package detect any instance of Winword.exe and ask the user to retry when word is closed
extract from the registry the word's option path
deploy the files into the word's startup folder
add an uninstaller in the local user add/remove programs
I put the package in the remote share. I also added a .ini file containing the last version of the package (in the form "1.0")
In the macro itself, I have a version number ("0.9" for example).
At the startup (AutoExec macro), I compare the local version to the remote version
I use shell exec to fire the setup if a newer version is found.
The setup will wait for Word to close
A bit tricky, but it works on Word 2K3 and Word 2K10.
I am using VB.net 2010 and I have two projects: SQLtesting and Controls. Their physical locations are:
C:\My Documents\Visual Studio 2010\Projects\SQLtesting\SQLtesting\ [forms reside here]
C:\My Documents\Visual Studio 2010\Projects\Controls\Controls\ [forms reside here]
The code shown below works fine. I run it from the project SQLtesting. It loads a listbox and a checkedlistbox with the controls found on a form. I can change the value of the ProjAndForm field to any form within the SQLtesting project and get the form's controls. The forms are not actually opened/shown and they are not suppose to be.
I would like to be able to access forms in other projects i.e.
*C:\My Documents\Visual Studio 2010\Projects\Controls\Controls*
while running the code from the SQLtesting project.
In actual use, (when this application is an .exe) the user (developer) will enter the Project Name, Form name and whatever else this requires and click on Button7. There cannot be any hardcoding as in my example code. This application will be installed on individual pc's or on a network so the code must work based on what the developer enters.
What I really need is a way to POINT to another project and form and still use my code.
I believe the statements needed would precede the following 3 statements I have.
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = Type.GetType(ProjAndForm, True, True)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
Currently, if I change the value of ProjAndForm to "Controls.Form66" an exception is thrown on the FormInstanceType statement.
Could not load type 'Controls.Form66' from assembly 'SQLtesting,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
As I said above, the code works fine and provides exactly what I want as long as I
reference a form in the current project SQLtesting.
Can anyone help me with this?
Thank you.
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button7.Click
Dim CtlType As Type
Dim FormInstanceType As Type
Dim index As Integer
Dim objForm As Form
Dim ProjAndForm As String
Dim TypeName1 As String
Dim TypeName2 As String
ListBox1.Sorted = True
ListBox1.Items.Clear()
CheckedListBox1.Sorted = True
CheckedListBox1.Items.Clear()
CheckedListBox1.CheckOnClick = True
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = Type.GetType(ProjAndForm, True, True)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
For Each ctl As Control In objForm.Controls
CtlType = ctl.GetType
TypeName1 = CtlType.ToString.Substring(21) ' Remove system.windows.forms prefix
index = CheckedListBox1.FindStringExact(TypeName1)
If index = -1 Then
CheckedListBox1.Items.Add(TypeName1)
End If
TypeName1 = TypeName1 & ":" & ctl.Name & ":" & ctl.Text
ListBox1.Items.Add(TypeName1.ToString)
Next ctl
End Sub
What you are looking for is Assembly.LoadFrom. You will need the exe or dll for this.
Dim path As String = "youassemblywitpath.dll"
Dim ass As Assembly = Assembly.LoadFrom(path)
ProjAndForm = "SQLtesting.Form1"
FormInstanceType = ass.GetType(ProjAndForm)
objForm = CType(Activator.CreateInstance(FormInstanceType), Form)
or you could use MEF.
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?
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.