如何从c#中检测excel的打开实例 [英] How to detect open instance of excel from c#

查看:223
本文介绍了如何从c#中检测excel的打开实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个c#程序,我需要连接并在程序中使用excel实例。我的代码是:



Hi I have a c# program, I need to connect to and use an instance of excel from within the program. My code is:

Microsoft.Office.Interop.Excel.Application exApp = null;
try
{
  exApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception err)
{
   MessageBox.Show("no excel running, starting new one");
}
if (!exApp.Visible)
{
   exApp = new Microsoft.Office.Interop.Excel.Application();
}





我启动excel,然后启动c#程序,并执行try / catch块的catch部分。然后我的程序启动一个新的excel实例。所以现在我有两个excel运行实例,一个我用手工启动的实例,以及一个由我的程序启动的实例。当我再次触发此代码时,c#程序找到它启动的excel实例,并且我没有看到没有excel running ...消息。看来getactiveobject的调用仅在我的程序启动了excel的实例时才有效...帮助!我希望我的程序找到excel的任何实例,而不仅仅是它开始的那个......(对c#,。net,...来说是新的)THanks!



I start excel, then start the c# program, and the catch part of the try/catch block executes. My program then starts a new instance of excel. So now I have 2 instances of excel running, the one that I started maually, and the one started by my program. When I trigger this code again, the c# program finds the instance of excel that it started, and I don't see the "no excel running..." message. It seems that the call to getactiveobject only works if my program started the instance of excel... help! I want my program to find any instance of excel, not just the one that it started... (kind of new to c#, .net, ...) THanks!

推荐答案

尝试 Marshal.GetActiveObject [ ^ ]方法如下所述:以编程方式启动Office应用程序 [ ^ ]
Try Marshal.GetActiveObject[^] method as is described here: Launching Office Apps Programmatically[^]


查看此CodeProject文章在C#中查找和列出流程 [ ^ ]



以前类似的问题 King_Fisher [ ^ ]也建议此链接http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-running [< a href =http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-runningtarget =_ blanktitle =New Window> ^ ]。如果这最后一个链接对您有用,那么King_Fishers解决方案是这里 [ ^ ]
Have a look at this CodeProject article Finding and Listing Processes in C#[^]

On a similar question previously King_Fisher[^] also suggested this link http://stackoverflow.com/questions/4722198/checking-if-windows-application-is-running[^]. If this last link works for you then King_Fishers solution is here[^]


这篇关于如何从c#中检测excel的打开实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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