13

Currently my code uses

SurferApp = Marshal.GetActiveObject("Surfer.Application") as Surfer.Application

to get the running instance of a software called surfer, for the sake of simplicity we can replace Surfer to Word that everyone knows about. Now let's say I have 2 MS word application running and I want to get both of them using Marshal.GetActiveObject(), how can I get both the running instances and associate each with a separate object?

kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
hoooman
  • 580
  • 3
  • 6
  • 15

2 Answers2

14

Marshal.GetActiveObject returns the first instance it finds on ROT (running object table). If you have more than one instance running with the same name/id, you have to get it directly from ROT.

A few links to start:

sarh
  • 6,371
  • 4
  • 25
  • 29
Lukas Winzenried
  • 1,919
  • 1
  • 14
  • 22
0

The accepted answer contains only links. I have extracted the shortest answer possible from the cited material. I give you a MarshalGetActiveObject function that works the same way the old Marshal.GetActiveObject did.


[DllImport("oleaut32.dll", PreserveSig = false)]
private static void GetActiveObject(ref Guid rclsid, IntPtr pvReserved, [MarshalAs(UnmanagedType.IUnknown)] out object ppunk)

[DllImport("ole32.dll")]
private static int CLSIDFromProgID([MarshalAs(UnmanagedType.LPWStr)] string lpszProgID, out Guid pclsid)

public static object MarshalGetActiveObject(string progId)
{
    Guid clsid;
    object obj = null;
    if (CLSIDFromProgID(progId, out clsid) == 0)
        GetActiveObject(ref clsid, IntPtr.Zero, out obj);

    return obj;
}

HackSlash
  • 4,944
  • 2
  • 18
  • 44