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

查看:56
本文介绍了创建 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.Application 替换为 CorelDRAW.ApplicationClass,因为当我浏览 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.

我怎样才能让它工作?谢谢!

How can I get this to work? Thank you!

推荐答案

您可以使用以下结构创建已注册 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.

使用 dynamic 关键字,这样您就可以像调用真正的 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天全站免登陆