Samples | System } else { result[candidateName] = ide; } } return result; } public static DTE AttachToExistingDte(string solutionPath, string progId) { Hashtable dteInstances = GetIDEInstances(false, progId); IDictionaryEnumerator enumerator = dteInstances.GetEnumerator(); while (enumerator.MoveNext()) { DTE dte = enumerator.Value as DTE; if (dte?.Solution.FullName == solutionPath) { Console.WriteLine($"Found solution: {dte.Name}"); return dte; } } return null; } } There are several ways to use the class and establish a connection to a specific TwinCAT instance. Generally, GetRunningObjectTable() first returns a snapshot of all registered COM objects.
GetIDEInstances() filters the DTE instances based on the ProgID, and AttachToExistingDte() then selects the instance whose open solution matches the path being searched for. This allows you to specifically address one of several concurrently running IDE instances, for example, when multiple TwinCAT projects are open at the same time on an engineering computer. Example: Connection via the solution path: //Reading all running dte objects and displaying them in te console System.Collections.Hashtable runningObjects = DteHelper.GetRunningObjectTable(); Console.WriteLine("Running COM objects:"); foreach (System.Collections.DictionaryEntry entry in runningObjects) { Console.WriteLine($"Name:
{entry.Key}, Type: {entry.Value.GetType().FullName}"); } //Attach to specific dte with matching solution path DTE dte = DteHelper.AttachToExistingDte( @"C:\Users\Admin\Documents\TcXaeShell\TwinCAT Project1\TwinCAT Project1.sln", "TcXaeShell.DTE.17.0" ); Reading all TwinCAT instances and selecting one // Reading all runnning TcXaeShells Hashtable instances = DteHelper.GetIDEInstances(true, "TcXaeShell.DTE.17.0"); IDictionaryEnumerator enumerator = instances.GetEnumerator(); //Enumerating through all found shells while (enumerator.MoveNext()) { //Get DTE and check wether its the correct DTE or not DTE dte = enumerator.Value as DTE; Console.WriteLine(dte?.Solution.FullName); // e.g.
C:\Projects\MyProject\MyProject.sln } 6.3.6 Avoiding COM exceptions caused by incorrect Thread Apartments | Avoiding COM exceptions caused by incorrect Thread Apartments The Automation Interface COM object must be run in STA. STA stands for Single-Threaded Apartment. The reason lies in the COM threading model. STA-registered objects expect all calls to be serialized via the same thread that created the object. Code that runs in MTA threads – for example, BackgroundWorker , ThreadPool , or Task.Run – violates this rule and causes RPC_E_SERVERCALL_RETRYLATER exceptions TE1000 206 Version: 1.7.0