Bug fix #39: Rewrite wm_get_focused()

Rewrite wm_get_focused() and fix some other possible issues. Thanks to
Arkq for reporting.