Why this error and how to solve it ??

A

Andrew

Hello, friends,

We are developing a C#.net (2005) application, which will use Excel to view
..xls files.

I created a WindowForm. In one of its methods, I instantiated Excel like the
follows:

public void LoadExcelWorkBook(string fullPathFileName)
{
if (currentFileName == fullPathFileName)
return;

currentFileName = fullPathFileName;

if (ea == null) ea = new
Microsoft.Office.Interop.Excel.ApplicationClass();

if (excelWnd == 0) excelWnd = FindWindow("XLMAIN", null);
if (excelWnd != 0)
{
SetParent(excelWnd, this.Handle.ToInt32());

try
{
ea.Visible = true;

SetWindowPos(excelWnd, this.Handle.ToInt32(), 0, 0,
this.Bounds.Width, this.Bounds.Height, SWP_NOZORDER | SWP_NOMOVE |
SWP_DRAWFRAME | SWP_NOSIZE);

}
catch
{
MessageBox.Show("Error!");
}

}
}

where:

public Microsoft.Office.Interop.Excel.Workbook wb = null;
public static Microsoft.Office.Interop.Excel.ApplicationClass ea =
null;
public static int excelWnd = 0;
public static string currentFileName = "";

were declared in the same class.

In my WindowForm's Dispose(), I had source code like the follows, expecting
to clean up everything:

protected override void Dispose(bool disposing)
{
if (wb != null)
{
object saveChanges = false;
object fileName = System.Reflection.Missing.Value;
object routeWorkbook = System.Reflection.Missing.Value;
wb.Close(saveChanges, fileName, routeWorkbook);

System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
wb = null;
}
if (ea.Workbooks != null)
{
ea.Workbooks.Close();
}
if (ea != null)
{
ea.Quit();

System.Runtime.InteropServices.Marshal.ReleaseComObject(ea);
ea = null;
}
DestroyWindow(excelWnd);
GC.Collect();

if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

It could launch Excel and made it as a child of my WindowForm window without
problem.

However, when I closed the app, everything was closed successfully but with
an error message popup window: Saying "Microsoft Office Excel has encountered
a problem and needs to close. We are sorry for the inconvenience." with
"Send Error Report" and "Don't Send" command buttons.

I then took out
SetParent(excelWnd, this.Handle.ToInt32());
This time, Excel was launched as an independent window, no longer a child of
the previous WindowForm. And, when I closed the app, everything was closed
without any error message.

I could not understand this and could not figure out why!

Anyone has any ideas? How to make it error free when making Excel a child
window in our app's WindowForm? Any reference papers?

Thanks a lot for your help.
 
N

NickHK

Andrew,
I've done similar in VB6. Prior to close reset Excel's parent:

SetParent excelWnd, 0

NickHK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top