How to determine the visible window that has the user focus?

If an application has more than one visible window (e.g. a text input window and a font window):
How is it possible to find the window that has the user focus?

Here’s my current code snippet (not working in all cases):

-- determine the front window
on getFrontWindow()
	
	tell application "System Events"
		set applicationName to name of every process whose frontmost is true and visible ≠ false
		
		-- the front window is not always the main window
		set theWindow to front window of application process (applicationName as text)
		if ((title of theWindow) is equal to "") then
			-- determine the next window with a title
			set theWindows to (every window of application process (applicationName as text))
			repeat with theWindow in theWindows
				if ((title of theWindow) is not equal to "") then exit repeat
			end repeat
		end if
	end tell
	
	return theWindow
end getFrontWindow

Remarks:

  • The code snippet looks for a (first) window which has a window title.
  • That is in most (but not all) cases the front window which has the user focus.