static void Main(string[] args) { try { //Get the static instance already running app = MyApplication.GetApiInstance(); //This line doesn't work. Gives an error about casting __comobject //I also can't cast app to MyApplication (gives the same error //app.MyApplicationClose += OnAppClose; Console.WriteLine("Val = " + app.GetVal().ToString()); Console.WriteLine("Val = " + app.GetVal().ToString()); } catch (COMException ex) { Marshal.ThrowExceptionForHR(ex.ErrorCode); } }
//Will look for an existing instance in the ROT and return it public static ICOMApplication GetApiInstance() { Hashtable runningObjects = Ole32.GetRunningObjectTable(); IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator(); while (rotEnumerator.MoveNext()) { string candidateName = (string)rotEnumerator.Key; if (!candidateName.Equals("!MyNamespace.ICOMApplication")) { continue; } ICOMApplication wbapi = (ICOMApplication )rotEnumerator.Value; if (wbapi != null) { return(wbapi); } //TODO: Start the application so it can be added to com and retrieved for use } return(null); }