创建一个COM互操作类的实例

4

我正在尝试使用C#从我的程序中打开CorelDRAW。到目前为止,我已经通过引用适当的COM库并调用相应的方法来实现了这一点。

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

然而,我希望我的程序可以与支持互操作性的任何CorelDRAW版本一起使用。为了在运行时加载相应的dll文件以匹配正确的版本,我尝试使用反射来加载互操作库。通过查找资料,我已经尝试了以下方法。

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...失败。
我该如何使其工作?谢谢!

我已经在某种程度上让它工作了。我在我的C#解决方案中创建了5个附加项目,每个项目都包含对特定版本Corel的引用。然后该项目具有返回我的CorelDRAW.Application对象的函数。然后我可以在主程序中对该对象使用反射。虽然不是最干净的方法,但目前已足够。 - Ben Bartle
3个回答

5
您可以使用以下语法创建已注册的 ActiveX 对象实例:
Type type = Type.GetTypeFromProgID("CorelDRAW.Application", true);
object vc = Activator.CreateInstance(type);

那么你有三个选项,可以如何处理返回的对象。
  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.

  2. Reflection, which you mention in your question.

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

我实际上花了6个小时搜索这个答案,我的代码是有效的,但没有窗口出现在屏幕上,秘密就是将Visible属性设置为true,谢谢。 - fellyp.santos

1
  System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(fullPath);
  dynamic app = assembly.CreateInstance("CorelDRAW.ApplicationClass", true);

这将会起作用。

0

我知道这是一个非常(极其)老的问题,但我认为发布一些更新的代码对于未来像我一样遇到困难的程序员会有所帮助。

CorelDraw 2021

Type corelType = Type.GetTypeFromProgID("CorelDRAW.Application.23");

Application app = (Application)Activator.CreateInstance(desktopType);

app.Visible = true;

Console.ReadLine(); // Needed in console project to keep CorelDraw opened

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接