metalcam
metalcam

Reputation: 402

Load Excel process and close the entire process when closing a document

In my C# application, I can Open a new Excel process by clicking a button. Then, it waits for input idle and load a new Excel file. I have to accomplish it because I want all macros and tools to be loaded before loading my document (otherwise, there is a rendering bug).

The Process Id is saved in a var, and when I click again on that button, with the PID, if the process already exists, the Process has the focus, otherwise, a new process is created :

Process processExcel = null;

if (pId_m.HasValue)
{
    try
    {
        processExcel = Process.GetProcessById(pId_m.Value);
    }
    catch (Exception ex)
    {
        Log.MonitoringLogger.Error("Unable to find Pid : " + pId_m,ex);
    }
}

if (processExcel != null && (processExcel.HasExited == false))
{
    AutomationElement element = AutomationElement.FromHandle(processExcel.MainWindowHandle);
    if (element != null)
    {
        element.SetFocus();
    }
}
else
{
    ProcessStartInfo info = new ProcessStartInfo();
    info.FileName = "Excel.exe";
    info.Arguments = " /e ";
    processExcel_l = Process.Start(info);
    pId_m = processExcel_l.Id;
    processExcel_l.WaitForInputIdle();
    processExcel_l.StartInfo = new ProcessStartInfo(path);
    processExcel_l.Start(); 
}

The problem is the following : when I close the Excel document window (and not Excel window), and I click the button, the focus is set to the Excel process, but without any document... This behavior is logic, but not working for what I want...

I have seen a software that load a new process and a new document inside, but when clicking on the document close button, the entire process was exited... How to reproduce the same?

Edit : Ok,

Finally instead of setting the focus on the process, I launched a file on this process (which set focus if the file is already open).

It's not what I really wanted to do, but it solve my problem...

Upvotes: 0

Views: 1231

Answers (2)

Adam Driscoll
Adam Driscoll

Reputation: 9483

I would suggest utilizing the Excel COM model rather than running the process by hand. You can subscribe to events of the Worksheet and close the application.

These MSDN documents might be helpful:

http://msdn.microsoft.com/en-us/library/wss56bz7(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.worksheet_members.aspx

Upvotes: 1

Samich
Samich

Reputation: 30175

Wait for Excel process ending and then close your app:

processExcel_l.WaitForExit();
Application.Exit();

To handle closing only Excel document (not Excel process) you probably need to reference to Excel API.

Upvotes: 0

Related Questions