开发者

How to stop an Excel process that I started from a C# .Net application?

开发者 https://www.devze.com 2022-12-21 03:25 出处:网络
I\'m running Excel from a C# .Net application and having trouble 开发者_开发问答getting the process to shut down.How can I get the Excel process to shut down correctly from my C# program?Try this:

I'm running Excel from a C# .Net application and having trouble 开发者_开发问答getting the process to shut down. How can I get the Excel process to shut down correctly from my C# program?


Try this:

foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            if (process.MainModule.ModuleName.ToUpper().Equals("EXCEL.EXE"))
            {
                process.Kill();
                break;
            }
        }


I'm about 99% certain that your problem is caused by dangling COM references preventing the Excel process from shutting down. Excel is particularly prone to this as it tends to transparently generate COM references without giving you the means to get at their handles and explicitly shut them down.

The PIAs compound this problem by making their own set of references to the underlying COM objects that they do not clean up unless you explicitly make them do it. Working with Excel through the PIAs is quite fiddly for precisely this reason.

Application.Quit() (IIRC this is what it's called) will shut down the process if the references are all correctly cleaned up. This means that you have to carefully manage the life cycle of anything that holds COM references to the Excel process and make sure that all COM references are cleaned up properly.


Application app = new Application();
...
EndTask((IntPtr)app.Hwnd, true, true);

[DllImport("user32.dll")]
public static extern bool EndTask(IntPtr hwnd, bool shutdown, bool force);


Depending on your needs, you might consider using SpreadsheetGear for .NET which gives you an Excel compatible component with no COM Interop (no hanging instances, better performance, don't have to worry whether Excel is installed or which version of Excel is installed).

You can see live ASP.NET samples with C# and VB source here, learn more about SpreadsheetGear's Windows Forms controls and samples here, and download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

0

精彩评论

暂无评论...
验证码 换一张
取 消