问题
I am starting an Excel application using the Process
class. I am able to get the process id & the main window handle with the code below.
Process xlP = Process.Start("excel.exe");
int id = xlP.Id;
int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle;
So this starts an Excel application. How do I reference this particular instance of Excel with the process id & main window handle?
I have seen similar questions on here but the answer was a link to a webpage that no longer exists.
I basically want something like below.
oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
Please not the Excel application has to be started using the Process.Start
method, no if buts or maybes.
回答1:
You can use the following code to access all running Excel instances and display the Window Handle they use:
[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
private void button1_Click(object sender, EventArgs e)
{
IRunningObjectTable lRunningObjectTable = null;
IEnumMoniker lMonikerList = null;
try
{
// Query Running Object Table
if (GetRunningObjectTable(0, out lRunningObjectTable) != 0 || lRunningObjectTable == null)
{
return;
}
// List Monikers
lRunningObjectTable.EnumRunning(out lMonikerList);
// Start Enumeration
lMonikerList.Reset();
// Array used for enumerating Monikers
IMoniker[] lMonikerContainer = new IMoniker[1];
IntPtr lPointerFetchedMonikers = IntPtr.Zero;
// foreach Moniker
while (lMonikerList.Next(1, lMonikerContainer, lPointerFetchedMonikers) == 0)
{
object lComObject;
lRunningObjectTable.GetObject(lMonikerContainer[0], out lComObject);
// Check the object is an Excel workbook
if (lComObject is Microsoft.Office.Interop.Excel.Workbook)
{
Microsoft.Office.Interop.Excel.Workbook lExcelWorkbook = (Microsoft.Office.Interop.Excel.Workbook)lComObject;
// Show the Window Handle
MessageBox.Show("Found Excel Application with Window Handle " + lExcelWorkbook.Application.Hwnd);
}
}
}
finally
{
// Release ressources
if (lRunningObjectTable != null) Marshal.ReleaseComObject(lRunningObjectTable);
if (lMonikerList != null) Marshal.ReleaseComObject(lMonikerList);
}
}
回答2:
Add a reference to Microsoft.Office.Interop.Excel and use the following code:
Process xlP = Process.Start("excel.exe");
int id = xlP.Id;
int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle;
Excel.Application oExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
if(xlP.MainWindowTitle.Contains( oExcelApp.ActiveWorkbook.Name) )
{
//Proceed further
}
来源:https://stackoverflow.com/questions/35366658/retrieve-excel-application-from-process-id