C# Unable to get ProcessId of Excel Object

M

MattC

I'm trying to get the process ID of an Excel object I've created but It
always returns 0???

TIA

MattC

using System.Diagnostics;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

public class WebForm2 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{


Excel.Application xl = new Excel.ApplicationClass();
int _mExcelPID = 0;
int handle = xl.Hwnd;
GetWindowThreadProcessId(handle, ref _mExcelPID);
xl.Application.DisplayAlerts = false;
Excel.Workbook wb;
Excel.Worksheet ws;
wb = xl.Workbooks.Add(Type.Missing);
ws = (Excel.Worksheet)wb.Worksheets[1];
ws.Cells[3,4] = "Test";
wb.SaveAs(
Server.MapPath(@"\automation\bin\test.xls"),
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
wb.Close(Type.Missing, Type.Missing, Type.Missing);
try
{
//
// Close the Excel application.
// Tell the stupid interop layer to release the object.
//
xl.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xl);
}
finally
{
//
// Prevent an orphaned Excel process by forcibly killing it.
//
xl = null;
KillProcess(_mExcelPID);
}

}

[DllImport("user32")]
public static extern int GetWindowThreadProcessId(int hwnd, ref int
lpdwProcessId);

private void KillProcess(int ProcessID)
{
Process [] aProcesses = Process.GetProcesses();
Process aProcess = null;
try
{
//
// Look for an Excel process matching the one we started.
//
for (int i = 0; i <= aProcesses.GetUpperBound(0); i++)
{
if (aProcesses.Id == ProcessID)
{
aProcess = aProcesses;
break;
}
}
try
{
//
// If we found a matching Excel proceess with no main window
// associated main window, kill it.
//
if (aProcess != null)
{
if (aProcess.ProcessName.ToUpper() == "EXCEL" && !aProcess.HasExited)
aProcess.Kill();
}
}
catch {}
}
catch {}
}

}
 

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