TROGDOR has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow Monks,

I'm trying to write a simple macro program to record and playback user input (keystrokes, mouse movements and button clicks). I'm having trouble reading keystrokes and button clicks that are not in the perl window. Specifically, I'd like to run the perl progam from a command prompt, then move over to another window (losing focus on the command prompt), but still read the mouse movements, button clicks, and keystrokes. I plan to run this on a Win32 XP box, so my target modules are either Win32::GUI or PerlTk.

Here's what I've discovered so far:

  • Win32::GUI::GetCursorPos works great for reading the location of the mouse at the root level, regardless of which window has the focus.
  • There doesn't seem to be a way to read keystroke events in Win32::GUI.
  • I've avoided using Term:ReadKey, as this module says it won't work in a Windows environment.
  • Term::Getch works okay, but it won't work once focus is lost from the execution window. Also, it only returns ASCII characters, so it can't read function keys.
  • PerlTK has a nice binding interface for recognizing keystrokes and mouse button presses, but it only works when the Tk main window has focus.
  • Win32::GuiTest works great for simulating mouse movement and button presses, and does not require focus.

    Can anyone recommend a technique for reading user input when focus is lost?

    Thanks,
    TROGDOR
    • Comment on Reading root-level (unfocused) mouse and keyboard input
  • Replies are listed 'Best First'.
    Re: Reading root-level (unfocused) mouse and keyboard input
    by BrowserUk (Patriarch) on Dec 16, 2004 at 21:33 UTC

      The only way (that I'm aware of), of intercepting global events (keyboard mouse ect.) is to install a System level Hook using SetWindowsHookEx.

      Whilst theoretically possible to do this from Perl, it is distinctly non-trivial as hook procedures need to be callback routines located in a .dll. You really need to drop to C or assembler for this.


      Examine what is said, not who speaks.        The end of an era!
      "But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
      "Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
      "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon