Convert COM object to .Net Object

2019-08-09 19:02发布

public int Set(int newValue,Object obj)
{
  //System.Windows.Forms.Control ctrl = (System.Windows.FormsControl)Object;
}

The Object here is COM object. Now I want to convert it to a .NET object and get hold of its properties. What is the easiest way to do it?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-09 19:58

The fact that the object in question is a COM object is not a problem. You don't have to convert it to a .NET object because it already is one. You get hold of the properties on this object as you would any other .NET object for which you didn't have type information, for example:

var objectType = obj.GetType();

foreach(var prop in objectType.GetProperties())
{
    Console.WriteLine("Property {0} of type {1}", 
                        prop.Name, prop.PropertyType.Name);
}

To invoke a property you can use the InvokeMember method of the Type class. Here's how to set the "Visible" property (if it exists) on your object to true:

objectType.InvokeMember("Visible", BindingFlags.SetProperty, 
                               null, obj, new object[] { true });

If you're using .NET 4 or 4.5, you can use the dynamic keyword to make working with COM originated .NET objects easier:

var xlAppType = Type.GetTypeFromProgID("Excel.Application");

dynamic xlApp = Activator.CreateInstance(xlAppType);

xlApp.Visible = true;

Note how the invocation of the Visible property was incantation-free in that last example. I try to use dynamics whenever possible to work with COM objects these days.

查看更多
Fickle 薄情
3楼-- · 2019-08-09 20:04

You can't convert a COM object into a Windows.Forms.Control object directly. It isn't that specific type.

The COM object should, if you use the correct type library, provide you with properties of its own. You should be able to use its properties directly, provided you cast it to the appropriate type.

查看更多
登录 后发表回答