using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; namespace Yaulw.Win32 { /// /// COM Win32 Helper Functions /// public static class COM { /// /// Returns a pointer to an implementation of IBindCtx (a bind context object). This object stores information about a particular moniker-binding operation /// /// This parameter is reserved and must be 0 /// Address of an IBindCtx* pointer variable that receives the interface pointer to the new bind context object. /// This function can return the standard return values E_OUTOFMEMORY and S_OK [DllImport("ole32.dll")] public static extern int CreateBindCtx(int reserved, out IBindCtx ppbc); /// /// Use this to retrieve the Actice COM Object from the ROT, for the specified progId /// /// /// a valid com object, or null if error occured public static Object GetActiceCOMObject(string progId) { Object app = null; try { app = Marshal.GetActiveObject(progId); } catch (SystemException) { /* ignore */ } return app; } /// /// ROT Object Entry /// public struct RunningObject { public string name; public object o; } /// /// Use this to Get All Running Objects in the ROT /// /// list of all Runnint Objects in the ROT public static List GetRunningObjects() { // Get the table. var res = new List(); IBindCtx bc; CreateBindCtx(0, out bc); IRunningObjectTable runningObjectTable; bc.GetRunningObjectTable(out runningObjectTable); IEnumMoniker monikerEnumerator; runningObjectTable.EnumRunning(out monikerEnumerator); monikerEnumerator.Reset(); // Enumerate and fill our nice dictionary. IMoniker[] monikers = new IMoniker[1]; IntPtr numFetched = IntPtr.Zero; while (monikerEnumerator.Next(1, monikers, numFetched) == 0) { RunningObject running; monikers[0].GetDisplayName(bc, null, out running.name); runningObjectTable.GetObject(monikers[0], out running.o); res.Add(running); } return res; } /// /// Use this to Get A specific type of Object from the ROT /// /// List of a specific type of Object in the ROT public static List GetRunningObjectsOfType() { // Get the table. var res = new List(); IBindCtx bc; CreateBindCtx(0, out bc); IRunningObjectTable runningObjectTable; bc.GetRunningObjectTable(out runningObjectTable); IEnumMoniker monikerEnumerator; runningObjectTable.EnumRunning(out monikerEnumerator); monikerEnumerator.Reset(); // Enumerate and fill our nice dictionary. IMoniker[] monikers = new IMoniker[1]; IntPtr numFetched = IntPtr.Zero; while (monikerEnumerator.Next(1, monikers, numFetched) == 0) { object o; runningObjectTable.GetObject(monikers[0], out o); if (o is T) res.Add((T)o); o = null; } return res; } } }