You can create the following class to your project (referencing System.Runtime.InteropServices).
public class MarshalExtension
{
[DllImport("ole32")]
private static extern int CLSIDFromProgIDEx(
[MarshalAs(UnmanagedType.LPWStr)] string lpszProgID,
out Guid lpclsid);
[DllImport("oleaut32")]
private static extern int GetActiveObject(
[MarshalAs(UnmanagedType.LPStruct)] Guid rclsid,
IntPtr pvReserved,
[MarshalAs(UnmanagedType.IUnknown)] out object ppunk);
public static object? GetActiveObject(string progId,
bool throwOnError = false)
{
ArgumentNullException.ThrowIfNull(progId);
var hr = CLSIDFromProgIDEx(progId, out var clsid);
if (hr < 0)
{
if (throwOnError)
Marshal.ThrowExceptionForHR(hr);
return null;
}
hr = GetActiveObject(clsid, IntPtr.Zero, out var obj);
if (hr < 0)
{
if (throwOnError)
Marshal.ThrowExceptionForHR(hr);
return null;
}
return obj;
}
}
Then, instead of: Marshal.GetActiveObject(progId); simply call:
MarshalExtension.GetActiveObject(progId);