附加到现有的Excel实例

我试图确定是否打开一个特定的文件运行Excel的实例,如果这样附加到它,所以我可以控制该实例。

我已经搜遍了,而我所得到的大部分都来自这个问题。 它有一个对另一个网站的参考,但不幸的是它已经死了,所以我不能读它。

我的代码到目前为止是;

//Is Excel open? if (Process.GetProcessesByName("EXCEL").Length != 0) { Process[] processes = Process.GetProcesses(); foreach (Process process in processes) { //Find the exact Excel instance if (process.ProcessName.ToString() == "EXCEL" && process.MainWindowTitle == ("Microsoft Excel - " + fileName)) { //Get the process ID of that instance int processID = (int)Process.GetProcessById(process.Id).MainWindowHandle; //Attach to the instance... Excel.Application existingExcel = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject(process.Id); } } } 

到目前为止,我已经设法得到我想要附加的实例的进程ID,但是在使用这个ID的时候我却迷失了方向。

任何想法如何进行?

Marshal.GetActiveObject()不会将进程标识作为参数。 你想要的是:

 Marshal.GetActiveObject("Excel.Application"); 

请注意,这并不需要跟踪过程,只需要一个。

如果可以有多个进程并想要附加到特定的进程,则会变得更加复杂。 这是另一个问题的答案。

http://blogs.msdn.com/b/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx上也有一篇很好的文章,对不同的方式有了更全面的描述启动excel。 请注意,并非所有这些工具都必须与Excel 2013保持同步,而对于所有Excel窗口而言,只有一个进程会使事情复杂化。 为了您的目的,但GetActiveObject解决scheme应该没问题。