Tuesday, May 22, 2007

The Shell Windows Collection of Internet Explorer Objects

As mentioned previously, you cannot use the WIN32OLE.connect method to connect to a running instance of Internet Explorer, as you would do, for example, with Excel or Word. I'll explain now how to do this via the Windows Shell.

First, here's the code snippet, which grabs an instance of IE that has this blog displayed...


for window in WIN32OLE.new('Shell.Application').Windows
begin
if window.Document.Title =~ /Ruby on Windows/
ie = window
end
rescue
end
end

The Windows Shell object includes a Windows method which returns a collection of all of the open windows that belong to the Shell...

shell = WIN32OLE.new('Shell.Application')
windows = shell.Windows

This is actually a collection of Internet Explorer objects, though some of these may be Internet Explorer web browser windows and others may be Windows Explorer windows.

To get a count of the number of windows, call the Count method...

windows.Count

To reference a member of this collection by index, call the Item method, passing it the (zero-based) index...

first_window = windows.Item(0)

Internet Explorer windows will normally have a Document object, which will have a Title property, so to find the IE window that you want to work with, iterate over the Windows collection and check the Document.Title value...

for window in windows
begin
if window.Document.Title =~ /Ruby on Windows/
ie = window
end
rescue
end
end

...and now you have your IE application object to work with as previously discussed.

Note that not all Shell Window objects will have a Document object, so (in the example above) wrapping the code within a begin... rescue... end block would handle the error that occurs with non-IE windows.

Make sense? Let me know if you have questions or comments, and thanks for stopping by!

3 comments:

Mason said...

Great blog Dave! It's nice to see a site focused on tools for Ruby and Windows.

I read through the text editor faq a bit. Have you ever tried InType? It is supposed to be similar to TextMate on the mac. http://intype.info/home/index.php

David Mullet said...

Thanks, Mason!

I'd not heard of Intype, but will check it out. I've used UltraEdit, JEdit, and a number of others over the years. SciTE is currently my editor of choice. It's lightweight but lacks some of the features of more resource-intensive editors such as JEdit, Komodo Editor, or the e text editor. 'e' has been getting a lot of good buzz lately. I've installed it but not worked with it yet.

Ike said...

Thanks,David, it helps.