Comment itérer dans une instance d’Excel c #

Je peux accéder à une instance d’Excel en mémoire à l’aide de Marshal.GetActiveObject. Mais cela retourne toujours l’instance la plus ancienne existante.

Je voudrais parcourir toutes les instances et pouvoir choisir celle à relier.

Quelqu’un peut-il aider avec cela s’il vous plaît.

Essaye ça.

List procs = new List(); procs.AddRange(Process.GetProcessesByName("excel")); 

Edit: Il existe un article qui implémente pleinement ceci à l’ adresse http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx . GetActiveObject retournera toujours le premier object de la table. En effet, Office n’enregistre pas de nouveaux objects. Vous devez obtenir l’application à partir des fenêtres enfants.

Edit: C’est le code qui a fonctionné pour moi.

 using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { [DllImport("Oleacc.dll")] public static extern int AccessibleObjectFromWindow( int hwnd, uint dwObjectID, byte[] riid, ref Microsoft.Office.Interop.Excel.Window ptr); public delegate bool EnumChildCallback(int hwnd, ref int lParam); [DllImport("User32.dll")] public static extern bool EnumChildWindows( int hWndParent, EnumChildCallback lpEnumFunc, ref int lParam); [DllImport("User32.dll")] public static extern int GetClassName( int hWnd, SsortingngBuilder lpClassName, int nMaxCount); public static bool EnumChildProc(int hwndChild, ref int lParam) { SsortingngBuilder buf = new SsortingngBuilder(128); GetClassName(hwndChild, buf, 128); if (buf.ToSsortingng() == "EXCEL7") { lParam = hwndChild; return false; } return true; } static void Main(ssortingng[] args) { Excel.Application app = new Excel.Application(); EnumChildCallback cb; List procs = new List(); procs.AddRange(Process.GetProcessesByName("excel")); foreach (Process p in procs) { if ((int)p.MainWindowHandle > 0) { int childWindow = 0; cb = new EnumChildCallback(EnumChildProc); EnumChildWindows((int)p.MainWindowHandle, cb, ref childWindow); if (childWindow > 0) { const uint OBJID_NATIVEOM = 0xFFFFFFF0; Guid IID_IDispatch = new Guid("{00020400-0000-0000-C000-000000000046}"); Excel.Window window = null; int res = AccessibleObjectFromWindow(childWindow, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), ref window); if (res >= 0) { app = window.Application; Console.WriteLine(app.Name); } } } } } }