Late binding and type problems in VB

I am trying to run my code that was originally created using Visual Studio through another application where late bindings are forbidden, and this option cannot be changed, unfortunately. I am very new to programming in general and am struggling to figure this out. Here is the im code used in the code invocation phase:

Dim objIEShell As Object = CreateObject("Shell.Application") Dim objIEShellWindows As Object = objIEShell.Windows Dim objIEWin As Object For Each objIEWin In objIEShellWindows If InStr(objIEWin.LocationURL,"google")>0 Then objIEWin.Quit objIEWin = Nothing End If Next 

The code simply closes all instances of Internet Explorer with "google" in the URL. This is the error message that I get when trying to compile it:

 Message: Error compiling code error BC30574: Option Strict On disallows late binding. At line 2 error BC32023: Expression is of type 'Object', which is not a collection type. At line 4 

From the research that I have done so far, I understand that the first error message in line 2 refers to the type difference between objieshell and the Windows method. I think I need to convert objIEShell like this to CType(objIEShell,?) , but I don’t know the type of the .Windows method or how to find out. Also, any understanding of how to fix the second error will be very helpful, as I'm not sure where to start it.

+5
source share
1 answer

This dates back to when Microsoft was still planning on getting Explorer to act like a web browser. It makes it quite difficult to get the correct code; it is a combination of two separate COM components that are not very related to each other.

You need to first add two references to these components so that the compiler understands the names. Use Project> Add Link> COM tab and check "Microsoft Internet Controls" and "Microsoft Shell Controls and Automation". This adds Shell32 and SHDocVw namespaces.

Now you can write the early binding code as follows:

  Dim objIEShell = New Shell32.Shell Dim objIEShellWindows = CType(objIEShell.Windows, SHDocVw.IShellWindows) Dim objIEWin As SHDocVw.WebBrowser For Each objIEWin In objIEShellWindows If InStr(objIEWin.LocationURL, "google") > 0 Then objIEWin.Quit() End If Next 

The CType () expression is probably the most unintuitive; the Shell.Windows property is of type Object to break the dependency between the two components. Casting is necessary for voodoo to make the compiler happy.

+10
source

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


All Articles