创建一个COM互操作类的实例 [英] Creating an instance of a COM interop class

查看:144
本文介绍了创建一个COM互操作类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#从程序中打开CorelDRAW。到目前为止,我已经能够通过引用适当的com库并调用

I am trying to open CorelDRAW from within my program using C#. So far I have been able to do so by referencing the appropriate com library and calling

CorelDRAW.Application draw = new CorelDRAW.Application();
draw.Visible = true; 

但是,我希望我的程序可以与支持互操作的任何CorelDRAW版本一起使用。我正在尝试使用反射在运行时加载互操作库,在该库中可以为正确的版本选择特定的dll。通过环顾四周,我尝试了以下操作。

However, I would like my program to work with any version of CorelDRAW that supports interop. I am attempting to use reflection to load the interop library at runtime, where the specific dll can be chosen for the correct version. From looking around I have tried the following.

string path = "Interop.CorelDRAW.dll";
Assembly u = Assembly.LoadFile(path);
Type testType = u.GetType("CorelDRAW.Application");

if (testType != null)
{
    object draw = u.CreateInstance("CorelDRAW.Application");

    FieldInfo fi = testType.GetField("Visible");
    fi.SetValue(draw, true);
}

程序在 u.CreateInstance ...中失败失败,因为 CorelDRAW.Application 是一个接口,而不是一个类。我还尝试用 CorelDRAW.ApplicationClass 替换 CorelDRAW.Application ,因为当我浏览Interop.CorelDRAW时可以使用资源,但是 u.getType ... 失败。

The program fails at u.CreateInstance... fails because CorelDRAW.Application is an interface, not a class. I have also tried replacing CorelDRAW.Application with CorelDRAW.ApplicationClass as that is available when I browse through Interop.CorelDRAW as a resource, but then u.getType... fails.

如何使它工作?谢谢!

推荐答案

您可以使用以下结构创建已注册的ActiveX对象的实例:

You can create instances of registered ActiveX objects using following construct:

Type type = Type.GetTypeFromProgID("CorelDRAW.Application", true);
object vc = Activator.CreateInstance(type);

然后,您有3种选择如何处理返回的对象。

Then you have 3 options, on how to work with returned object.


  1. 将返回的对象投射到真正的CorelDRAW.Application接口,但是为此,您需要引用一些包含它的CorelDraw库,这可能会产生版本问题。

  1. Casting returned object to real CorelDRAW.Application interface, but for this you need to reference some CorelDraw library which contains it, and probably this will produce versioning problems.

反射,您在问题中提到过。

Reflection, which you mention in your question.

使用动态关键字,因此您可以像调用CorelDraw类/接口一样调用现有的方法和属性。

Use dynamic keyword, so you can call existing methods and properties just like it was a real CorelDraw class/interface.

Type type = Type.GetTypeFromProgID("CorelDRAW.Application", true);
dynamic vc = (dynamic)Activator.CreateInstance(type);
vc.Visible = true;


这篇关于创建一个COM互操作类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆