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?

1
  • 1
    Hi @hoooman, did you solve your problem. Maybe you could post some sample code.
    – Higune
    Dec 18, 2013 at 15:54

2 Answers 2

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:

0
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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.