Accessing window tabs in Visual Studio

The Visual Studio Automation Interface provides methods and properties to access active windows in Visual Studio. The following chapter demonstrates some sample code. However, we also suggest to investigate the webpages of the Microsoft Developer Network (MSDN) for more detailed information about the Visual Studio object model. This chapter provides sample code for the following tasks:

Accessing active windows

The DTE interface provides a property called "ActiveWindow", which returns the currently active window in Visual Studio as an object of type EnvDTE.Window.

Code Snippet (C#):

EnvDTE.Window activeWin = dte.ActiveWindow; 

Code Snippet (Powershell):

$activeWin = $dte.ActiveWindow

Closing active windows

Depending on the customers application, it may be necessary to close all active windows in Visual Studio before proceeding with the TwinCAT configuration via Automation Interface. The following code snippet closes all active windows but the "Solution Explorer".

Code Snippet (C#):

try
{
while (!dte.ActiveWindow.Caption.Contains("Solution Explorer"))
dte.ActiveWindow.Close();
}
catch (InvalidOperationException ex)
{
// use DTE.Quit() to close main window
}

Opening windows from TwinCAT PLC configuration

It is also possible to open windows from TwinCAT PLC, e.g. a visualization. The following code snippet opens an existing TwinCAT visualization from PLC project "Untitled1" and makes it the currently active window.

Code Snippet (C#):

string fileName = @"C:\TwinCAT Project1\TwinCAT Project1\Untitled1\VISUs\Visu.TcVIS";
dte.ItemOperations.OpenFile(fileName);

Code Snippet (Powershell):

$fileName = @"C:\TwinCAT Project1\TwinCAT Project1\Untitled1\VISUs\Visu.TcVIS"
dte.ItemOperations.OpenFile($fileName)