Attach to existing Excel Instance

安稳与你 提交于 2020-02-02 05:47:29

问题


I'm trying to determine whether or not an instance of Excel of running with a particular file open, and if so attach to it so I can control that instance.

I've searched around and the majority of what I've got have come from this question. It has a reference to another site, but unfortunately it's dead for me so I cannot read up on it.

My code so far is;

//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);                 
        }
    }
}

So far I've managed to get the process ID of the instance I want to attach to, but I'm lost when it comes to using that ID.

Any ideas on how to proceed?


回答1:


Marshal.GetActiveObject() doesn't take a process ID as a parameter. What you want is:

Marshal.GetActiveObject("Excel.Application");

Note that this doesn't require keeping track of the process at all, there just needs to be one.

It gets a lot more complicated if you can have multiple processes and want to attach to a specific one. That is where the answer to the other question comes in.

There is also a good article at http://blogs.msdn.com/b/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx with a more full description of different ways of launching excel. Note that not all of them are necessarily up to date with Excel 2013, where having a single process for all Excel windows complicates things. For your purposes though, the GetActiveObject solution should be fine.



来源:https://stackoverflow.com/questions/23655210/attach-to-existing-excel-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!