'Get active object from clsid C#

I've been looking for a simple way of obtaining an active object (on the ROT) with C#. I found Marshal.getActiveObject() but unfortunately this only takes a progid!

My current approach:

using System;
using System.Runtime.InteropServices;
public class COMHelper {
  [DllImport("oleaut32.dll", PreserveSig=false)]
  static extern void GetActiveObject(
                                        ref Guid   rclsid,
                                            IntPtr pvReserved,
    [MarshalAs(UnmanagedType.IUnknown)] out Object ppunk
  );
  [DllImport("ole32.dll")]
  static extern int CLSIDFromString(
     [MarshalAs(UnmanagedType.LPWStr)]      string lpszProgID,
                                        out Guid   pclsid
  );
  public static object getActiveObject(string sClsid){
    Guid clsid;
    CLSIDFromString(sClsid, out clsid);

    object obj;
    GetActiveObject(ref clsid, IntPtr.Zero, out obj);

    return obj;
  }
}
//...later...
COMHelper.getActiveObject("{a7161d1c-2ac0-4d5f-a56d-4043b5ce69a8}").whatever()

This is fine but it's quite chunky. I wondered, is there another built-in mechanism?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source