J?rgen Ahrens
6/4/2007 2:56:00 PM
Hi
I would like to attach to all running excel applications.
I tried
System.Runtime.InteropServices.Marshal.GetActiveObject()
you get an excel application but you can not specify which one, so this
doesn't work...
I tried
System.Runtime.InteropServices.Marshal.BindToMoniker()
But all Excel Application Monikers returned the same display name and
binding to the moniker always returned the same (i guess the first) excel
application object....
Finally i tried the following code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections;
using System.Runtime.InteropServices.ComTypes;
namespace Ascami.Axpo.EnergiemarktSimulator.WinApp
{
public class ExcelSelector
{
[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(uint reserved, out
IRunningObjectTable pprot);
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(uint reserved, out IBindCtx pctx);
/// <summary>
/// Will hold all excel applications that are currently running on this
machine.
/// </summary>
private static List<Excel.Application> excelApps = new
List<Excel.Application>();
/// <summary>
/// This function will bind to all currently running excel objects and store
the COM object within excelApps.
/// </summary>
public static void BindToRunningExcelObjects()
{
IRunningObjectTable runningObjectTable = null;
IEnumMoniker monikerList = null;
try
{
if (GetRunningObjectTable(0, out runningObjectTable) != 0 ||
runningObjectTable == null) return;
runningObjectTable.EnumRunning(out monikerList);
monikerList.Reset();
IMoniker[] monikerContainer = new IMoniker[1];
IntPtr pointerFetchedMonikers = IntPtr.Zero;
//Run through all monikers
while (monikerList.Next(1, monikerContainer, pointerFetchedMonikers) == 0)
{
IBindCtx bindInfo;
CreateBindCtx(0, out bindInfo);
//The following block does not work but isn't there any way?
//this may be the wrong iid. or do i have to use the iunknown?
Object boundComObject;
Guid iid = new Guid("000208D5-0000-0000-C000-000000000046");
try
{
monikerContainer[0].BindToObject(bindInfo, null, ref iid, out
boundComObject);
//Add the bound object to the list (I actually never got here...)
excelApps.Add((Excel.Application)boundComObject);
}
catch { }
Marshal.ReleaseComObject(bindInfo);
}
}
finally
{
if (runningObjectTable != null)
Marshal.ReleaseComObject(runningObjectTable);
if (monikerList != null) Marshal.ReleaseComObject(monikerList);
}
}
}
}
it didn't work... does anyone know a solution?
thanks for your help
jahrens