[python-win32] Get path of the current open document of the current active application

Tim Roberts timr at probo.com
Wed Sep 21 22:35:53 CEST 2011


Marte Soliza wrote:
>
> I'm looking for a way to, first, determine the current active
> application (i.e. the one with the top-most window). I think I got
> this now, but I'm not sure how much of this will help in my final goal
> which is to get the path of the current open document (for those that
> have them).
>
> I believe there is no single way to do this that will work for all
> applications, but is there a way to do this for most applications? Is
> there some convention that most applications follow to define what
> their current document is?
>
> If there's no general way, I'm willing to do this on an app-to-app
> basis starting with, say, MS Word.

This is an extremely difficult problem with no general case solutions.

I worked on a multi-year project for A Major Processor Manufacturer a
few years ago that tried to do this, in an attempt to create an
immersive, collaborative team environment.  They wanted to tell whether
several people were working on the same document.  We were able to
support Office and Internet Explorer, but that was pretty much it, and
even that was quite delicate.  It didn't always work, and it failed
after virtually every Office upgrade.  That's why the product has never
gone public.

One huge problem is that Windows, in general, does not have the concept
of a "document".  Some applications have a document-centric architecture
(although many do not), but there are no Win32 APIs about documents. 
The Office applications can be controlled by COM, but then you need to
map from a window handle to a COM object.

Now, it turns out that last problem is solvable.  The Office
applications all register themselves in the Running Object Table.  It's
possible to enumerate the monikers in the Running Object Table and
figure out which one maps to a particular window handle.  That gives you
the root application object, and you can ask that for the current
document, assuming the document has been saved.

For IE, you can actually go probing through the window handles to find
the text box that contains the current URL.

-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the python-win32 mailing list