Samples | System A running IDE instance is accessed via the operating system's Running Object Table (ROT). ROT is a system-wide table in which running COM servers are registered under a unique ProgID. Which ProgID is the correct one depends on the host – such as Visual Studio or TcXaeShell – and its version. For attachment to work, the requesting process and the IDE must run in the same user context and with the same elevation level, since the ROT is managed separately for each session. flowchart LR A[DTE object] --> B[Solution] B --> C[Projects.Item 1] C --> D[Object as ITcSysManager] Requirements TwinCAT XAE with Visual Studio or TcXaeShell is installed.
A Visual Studio or TcXaeShell instance is already running when GetActiveObject is used. C# sample For C# in .NET 5 and later, the corresponding Ole32 functions must be imported manually. The Marshal.GetActiveObject method is included in the classic .NET Framework, but was removed from the System.Runtime.InteropServices.Marshal type in .NET 5+. Call the underlying Win32 functions CLSIDFromProgID and GetActiveObject using P/Invoke. CLSIDFromProgID converts the human- readable ProgID – such as TcXaeShell.DTE.17.0 – into the binary CLSID, which GetActiveObject uses to look up the corresponding entry in the ROT. It makes sense to encapsulate these calls in a reusable helper class:
using System.Runtime.InteropServices; internal static class ComHelper { [DllImport("ole32.dll")] private static extern int CLSIDFromProgID( [MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid); [DllImport("oleaut32.dll")] private static extern int GetActiveObject( ref Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk); public static object GetActiveObject(string progId) { CLSIDFromProgID(progId, out Guid clsid); int hr = GetActiveObject(ref clsid, IntPtr.Zero, out object obj); Marshal.ThrowExceptionForHR(hr); return obj; } } This helper class can be used to access the currently running TwinCAT instance. The call returns the DTE object.
Via dte.Solution.Projects.Item(1).Object , you can obtain the ITcSysManager interface of the first project in the open solution. GetActiveObject requires that an instance with the specified ProgID is already running. Otherwise, the call fails with an MK_E_UNAVAILABLE HRESULT. The index Item(1) is 1-based. For solutions with multiple projects, you must specifically select the desired TwinCAT project. DTE dte = (DTE)ComHelper.GetActiveObject("TcXaeShell.DTE.17.0"); ITcSysManager sysManager = dte.Solution.Projects.Item(1).Object as ITcSysManager; PowerShell and the TwinCAT instance must have the same “Elevation Level”.
If TwinCAT is running as an administrator but PowerShell is not, or vice versa, the ROT entries are located in separate sessions and are not visible. TE1000 203 Version: 1.7.0