Calling a COM Component From C# (Late Binding)

Tools Used: .NET SDK

The .NET framework is a natural progression from COM since the two share many central themes including component reuse and language neutrality. For backward compatibility, COM Interop provides access to existing COM components without requiring that the original component be modified. When a .NET Framework developer wants to incorporate COM code into a managed application, he or she imports the relevant COM types by using a COM Interop utility for that purpose. Once imported, the COM types are ready to use. This is early binding , but some time u require late binding of object. You can do that too in .NET ie you can call COM object via late binding by using Namespace Reflection.

In this application we are trying to call Excel and make it visible by using late binding.

For late binding the Type Class of Reflectionb is used. This Type class has many methos to get the COM object like the one which we have used is GetTypeFromProgID("Application") , this method get the COM ID from the System Registry and then by using the STATIC class member of Activator.CreateInstance() we create a new instance of the COM object.

To invoke the methods, function and Properties of the COM object we have to use the InvokeMethod() of the Type object with proper settings, this methos takes many arguments of which the inportant one is the methos type ex property (get or set)in example we have used a set property for Excel.Visible to make the Excel application visible.

We will try to call Excel application from .NET environment. This is a late binding application for early binding you have to use RCW(RunTime Callable Wrraper) of COM Object  to do so use command line tool tblimp.

ex. c:\> tblimp <name.dll> /out:<name.dll>

Download the attachment. This is a console application. Here is the code which calls excel exe. 

//Variable
Type excel;
object[] parameter= new object[1];
object excelObject;
try
{
//Get the excel object
excel = Type.GetTypeFromProgID("Excel.Application");
//Create instance of excel
excelObject = Activator.CreateInstance(excel);
//Set the parameter whic u want to set
parameter[0] = true;
//Set the Visible property
excel.InvokeMember("Visible", BindingFlags.SetProperty, null, excelObject, parameter);
}
catch(Exception e)
{
Console.WriteLine("Error Stack {0} ", e.Message) ;
}
finally
{
//When this object is destroyed the Excel application will be closed
//So Sleep for sometime and see the excel application
Thread.Sleep(5000);
//Relaese the object
//GC.RunFinalizers()
}

Up Next
    Ebook Download
    View all
    Learn
    View all