Creating an instance of the COM interop class

I am trying to open CorelDRAW from my program using C #. So far, I could do this by referencing the appropriate com library and calling

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

However, I would like my program to work with any version of CorelDRAW that supports interoperability. I am trying to use reflection to load the interop library at runtime, where a particular dll can be selected for the correct version. From the look around I 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); } 

The program crashes when u.CreateInstance... fails because CorelDRAW.Application is an interface, not a class. I also tried replacing CorelDRAW.Application with CorelDRAW.ApplicationClass as it is available when I view Interop.CorelDRAW as a resource, but then u.getType... fails.

How can I make this work? Thanks!

+4
source share
2 answers

You can create instances of registered ActiveX objects using the following construction:

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

Then you have 3 options for working with the returned object.

  • Bringing the returned object into the actual CorelDRAW.Application interface, but for this you need to reference some CorelDraw library that contains it, and this will probably lead to versioning issues.

  • The reflection that you mentioned in your question.

  • Use a 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; 
+4
source
  System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(fullPath); dynamic app = assembly.CreateInstance("CorelDRAW.ApplicationClass", true); 

it will work

+1
source

Source: https://habr.com/ru/post/1440186/


All Articles