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 outputs 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 the TwinCAT PLC configuration

It is also possible to open TwinCAT PLC windows, e.g. a visualization. The following code snippet opens an existing TwinCAT visualization from the PLC project "Untitled1" and makes it the 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)