Bug fix #5: Fix broken event window detection

- Fix broken event window detection that uses ev.xany.window, which is not
  always reliable. Thanks to CossRooper for report.

- Code cleanup.