Red Swan
Red Swan

Reputation: 15545

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

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?

Upvotes: 1

Views: 5261

Answers (4)

Wil
Wil

Reputation: 11

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

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

Upvotes: 1

Joe Erickson
Joe Erickson

Reputation: 7217

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

Upvotes: 0

ConcernedOfTunbridgeWells
ConcernedOfTunbridgeWells

Reputation: 66612

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.

Upvotes: 4

Jojo Sardez
Jojo Sardez

Reputation: 8558

Try this:

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

Upvotes: 4

Related Questions