附加到现有的Excel实例 [英] Attach to existing Excel Instance

查看:175
本文介绍了附加到现有的Excel实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定一个特定文件运行的Excel实例是否打开,如果是这样的话,可以控制该实例。

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

到目前为止,我已经管理获取我要附加的实例的进程ID,但是在使用该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?

推荐答案

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

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.

http://blogs.msdn.com/b/andreww/archive/2008/11 /30/starting-or-connecting-to-office-apps.aspx ,详细介绍了不同的启动excel的方法。请注意,并不是所有这些都必须与Excel 2013最新,因为所有Excel窗体的单个进程都会使事情变得复杂。为了您的目的, GetActiveObject 解决方案应该是正常的。

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.

这篇关于附加到现有的Excel实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆