18.2 Exposing COM Objects to C#

When you instantiate a COM object, you are actually working with a proxy known as the Runtime Callable Wrapper (RCW). The RCW is responsible for managing the lifetime requirements of the COM object and translating the methods called on it into the appropriate calls on the COM object. When the garbage collector finalizes the RCW, it releases all references to the object it was holding. For situations in which you need to release the COM object without waiting for the garbage collector to finalize the RCW, you can use the static ReleaseComObject method of the System.Runtime.InteropServices.Marshal type.

The following example demonstrates how to change your MSN Instant Messenger friendly name using C# via COM Interop:

// RenameMe.cs - compile with:
//   csc RenameMe.cs /r:Messenger.dll
// Run RenameMe.exe "new name" to change your name
//   as it is displayed to other users.
// Run TlbImp.exe "C:\Program Files\Messenger\msmsgs.exe"
//   to create Messenger.dll
using System;
using Messenger;
class MSNFun {
    static void Main(string[ ] args) {
        MsgrObject mo = new MsgrObject( );
        IMsgrService ims = mo.Services.PrimaryService;
        ims.FriendlyName = args[0];

You can also work with COM objects using the reflection API. This is more cumbersome than using TlbImp.exe, but is handy in cases in which it's impossible or inconvenient to run TlbImp.exe. To use COM through reflection, you have to get a Type from Type.GetTypeFromProgID( ) for each COM type you want to work with. Then, use Activator.CreateInstance( ) to create an instance of the type. To invoke methods or set or get properties, use the reflection API, which is covered in Chapter 13:

using System;
using System.Reflection;
public class ComReflect {
  public static void Main( ) {
    object obj_msword;   // Microsoft Word Application
    Type wa = Type.GetTypeFromProgID("Word.Application", true);
    // Create an instance of Microsoft Word
    obj_msword = Activator.CreateInstance(wa);
    // Use the reflection API from here on in...

    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference