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. ...