Hi,
Basically, you may use GetActiveObject to get an instance of the excel
application.
However , if there are multiple instances of Excel running at the same
time, the
GetActiveObject() API function returns the instance startup first.
Theoretically, you can iterate the ROT for each individual instance, but
Office applications do not register themselves if another instance is
already in the ROT because the moniker for itself is always the same, and
cannot be distinguished. This means that you cannot attach to any instance
except for the first. However, because Office applications also register
their documents in the ROT, you can successfully attach to other instances
by iterating the ROT looking for a specific document, attaching to this
document, and then getting the Application object from this document.
The following two KB Articles describes the above steps in detail:
<HOWTO: Attach to a Running Instance of an Office Application>
http://support.microsoft.com/default.aspx?scid=kb;en-us;238975
<HOWTO: Get IDispatch of an Excel or Word Document from an OCX>
http://support.microsoft.com/default.aspx?scid=kb;EN-US;190985
On .NET, you need do some P/Invoke to enumerate the ROT,
the following code snippet may help. You may try casting the returned RCW
object of COM interface into the managed Interface defined in Office PIA to
execute methods.
<code>
using System.Runtime.InteropService;
[DllImport("ole32.dll")]
public static extern int GetRunningObjectTable(int reserved, out
UCOMIRunningObjectTable prot);
[DllImport("ole32.dll")]
public object[] ActiveObjectList(string moniker)
{
UCOMIRunningObjectTable prot;
UCOMIEnumMoniker pMonkEnum;
ArrayList list = new ArrayList();
int Fetched = 0;
Win32.GetRunningObjectTable(0, out prot);
prot.EnumRunning(out pMonkEnum);
pMonkEnum.Reset();
UCOMIMoniker[] pmon = new UCOMIMoniker[1];
while (pMonkEnum.Next(1, pmon, out Fetched) == 0)
{
UCOMIBindCtx pCtx;
Win32.CreateBindCtx(0, out pCtx);
string str;
pmon[0].GetDisplayName(pCtx, null, out str);
if (str.IndexOf(moniker) != -1)
list.Add(str);
Marshal.ReleaseComObject(pCtx);
} return list.ToArray();
}
</code>
Does it resolve problem?
Let me know if you have anything unclear or meet some problem on it.
Thanks!
Best regards,
Ying-Shen Yu [MSFT]
Microsoft Community Support
Get Secure! -
www.microsoft.com/security
This posting is provided "AS IS" with no warranties and confers no rights.
This mail should not be replied directly, please remove the word "online"
before sending mail.