jqwha
jqwha

Reputation: 1679

Windows Image Acquisition and COM

I'm experimenting with WIA scanning and I see C# code examples that include "dynamic" typing and use COM object creation e.g.

set Img = CreateObject("WIA.ImageFile")

and

dynamic imageFile = dialog.ShowAcquireImage(
                    WiaDeviceType.Scanner,...

Is that method because the examples are for scripting languages (I don't know much about COM)? i.e. if I'm using this in a WPF application, can I just use the WIA classes without any problems, or should I (do I have to) use COM?

ImageFile img = new ImageFile()

Thanks.

Upvotes: 0

Views: 1080

Answers (1)

Hans Passant
Hans Passant

Reputation: 942138

The first snippet is Basic, it definitely uses late-binding. The second snippet is C#, it uses a very oddball mix where the ImageFile return type is late-bound but "WiaDeviceType.Scanner" definitely appears to come from the WIA type library. In general it does not make much sense to mix. You either take a dependency on the type library or you wing it completely late-bound.

A type library is the exact equivalent to metadata in a .NET assembly. It is a machine-readable description of the types supported by the COM component. Just as you'd add a reference to a .NET assembly with Project > Add Reference, you'd do the exact same thing with a type library. You get a list of registered type libraries in the COM tab. You'd pick "Microsoft Windows Image Acquisition Library v2.0" in your case. Or you use the Browse button, type libraries are usually embedded in the DLL just like metadata is embedded in a .NET assembly, sometimes it is a separate .tlb file. You'd pick c:\windows\system32\wmp.dll in your case. Sometimes you have to convert the type library yourself with Tlbimp.exe, necessary when the conversion generates warnings.

Late-binding a COM server is the exact equivalent of using Reflection in .NET. And prior to C# version 4, it exactly looked like reflection as well, very painful. It has all the disadvantages of using reflection, you get no IntelliSense help, typing mistakes produce runtime errors and it is inefficient at runtime. It has one advantage, same one Reflection has, it is more resilient to version changes.

Which is not an advantage that's very useful when you use WIA, it has been stable for the past 10 years. Microsoft used to publish a back-ported version of WIA v2 for Windows XP but that was discontinued. If you still want to support XP then using late-binding so you can still clunk WIA v1 is an option. Don't do that.

Long story short, you'd definitely prefer using Project > Add Reference. It is much easier to write the code and you are much less likely to have to deal with inscrutable runtime errors.

Upvotes: 1

Related Questions