C# GetObject Method
Marshal.GetActiveObject gets a running instance of the specified object from the Running Object Table (ROT).
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
private void GetExcel()
{
try
{
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Marshal.GetActiveObject exposes the GetActiveObject COM API method from OLEAUT32.DLL; however, the latter expects a class identifier (CLSID) instead of the programmatic identifier (ProgID) expected by this method. To obtain a running instance of a COM object without a registered ProgID, use platform invoke to define the GetActivateObject COM method
The above works, however once you find the instance of the Excel process I can't figure out how to force it to be visible.
ReplyDeleteI've tried all sorts of things like setting the VISIBLE property to TRUE with no luck.
Ideas?
I'm using Windows Vista Ultimate 32 bits with Microsoft Excel 2007 and this code doesn't work. I tried Microsoft.VisualBasic.Interop.GetObject and didn't work too......................
ReplyDeleteIt works for me in 32 Bit Vista. Any way to reproduce the error you get! For example, is the Excel used by any other program?
ReplyDeleteNo, my Excel is not used by any other program. What I am trying to do it is simple in Visual Basic 6.0. I just want do manually open an Excel File, and after I want that my c# program read and write contents of this opened worksheet.
ReplyDeleteIf your code is working, could you show us how u implement? Or better: give us a sample that makes what I said above.
Thank You
Here are the ways that I have tried :
ReplyDeleteType 1:
foreach (System.Diagnostics.Process oXLApp in System.Diagnostics.Process.GetProcessesByName("Excel"))
{
MessageBox.Show(oXLApp.MainWindowTitle);
IntPtr xLHandle = oXLApp.Handle;
Type t1 = oXLApp.GetType();
Delegate oX2L = Marshal.GetDelegateForFunctionPointer (xLHandle, t1);
//String XLProgID = Marshal.GenerateProgIdForType(XLSafeType);
oXL = (Excel.Application)Marshal.GetActiveObject(oXLApp.Id.ToString());
//oXL = (Excel.Application)oXLApp.CreateObjRef ;
}
Type 2:
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
Excel.Workbook oWB = oXL.Workbooks.Open(sXLFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);