Solution 1:

What you want is libwnck (if you're just interested in windows) or libbamf (if you're interested in windows and the applications that own them).

Solution 2:

Another thing you can use is xdotool:

xdotool getwindowfocus

would return the Window ID of the focussed window, and:

xdotool getwindowfocus getwindowname

would tell you its name.