System.Activator.CreateComInstanceFrom

  • Thread starter Thread starter scorpion53061
  • Start date Start date
S

scorpion53061

Hello to all and hope everyone on holiday is enjoying themselves!!

I am studying this namespace and method. In the docs it says:

"Creates an instance of the COM object whose name is specified, using the
named assembly file and the constructor that best matches the specified
parameters."

The syntax is:

Public Overloads Shared Function CreateComInstanceFrom( _
ByVal assemblyName As String, _
ByVal typeName As String _
) As ObjectHandle
End Function

Is my understanding correct to say we could create an instance of say EXCEL
without add a reference in the project? Probably not but here is what I
tried to do. And yes I know it is easier to add a reference than to do it
this way. I am just the curious type.

CreateComInstanceFrom("EXCEL.EXE", "Microsoft.Office.Core")

No instance of EXCEL appeared in my Task List though. Any thoughts on this
method?
 
What you really want is:

Dim xApp As Object = Microsoft.VisualBasic.CreateObject("Excel.Application")

And while this will indeed create an instance without adding a reference,
you will have to operate on the object completely through late-bound
techniques, whether you use VB's native late-bound access (with Option
Strict Off) or Reflection. In either case, you'll get no intellisense and
lose all type safety.

-Rob Teixeira [MVP]
 
I know about late binding.

What is the purpose of System.Activator.CreateComInstanceFrom method? Do you
know of a code sample or can you devise one that uses it?
 
It's sort of the same thing I showed you, but it assumes you have a runtime
callable wrapper assembly.
You should be able to use this, for example, with the Office PIAs. But that
being the case, you're better off referencing the PIAs directly.

-Rob Teixeira [MVP]
 
Sure but indulge me for a second.....

If I were to use this could you show me how it would be written?

CreateComInstanceFrom("Excel.dll", "C:\Documents and Settings\Kelly
Martens\My Documents\Visual Studio
Projects\XMLSettingsDemo\obj\Interop.Excel.dll")

When I do this no instance shows in my task manager demonstrating that an
Excel instance is alive...Why or how did I write this wrong?
 
You should be getting an error.
The arguments are (assembly, typeName), which in this case would be the full
path to the DLL, followed by the type name, which has to be an exported type
that has a constructor (IOW, a class where the underlying COM object can be
instantiated from CoCreateInstance - for example, "Excel.ApplicationClass").
If you use this type name, you will see an instance of Excel.exe on the
running process list. However, this method gives you an object handle
instance, which is fine for dealing with cross-app-domain object
indirection, but stick to the Microsoft.VisualBasic.CreateObject method if
you want to directly call methods from this using late-bound calls or
reflection.

-Rob Teixeira [MVP]
 
Back
Top