Catching keystrokes under Windows

Peter Hansen peter at engcorp.com
Wed Nov 19 14:35:07 EST 2003


Olli Piepponen wrote:
> 
> I'm having a little problem catching keystrokes under Windows. I did a
> little research and found that with mscvrt.getch() one can cath a single
> key that is pressed. However this doesn't work when the program is run
> on the backround and not as the primary task. What I would like to have
> is a same sort of function that would also work when the program is being
> run on the background. I'm trying to implement a program that would listen
> for a certain key to be pressed and then start a timer that would *beep*
> after 30 seconds or so. I've everything else sorted out except how to
> catch the one key.
> 
> So is there an easy way like msvcrt.getch() is or does one have to start
> playing with the win32api module? If the win32api-module is needed for this
> task could you also explain how? Python is my first real programming
> language so I don't understand too much about C\C++ stuff. Examples would
> be highly appreciated.

You absolutely cannot use msvcrt for this, as it works only with console
programs (i.e. DOS window programs).

You do have to use the win32 stuff, but at that point it becomes mostly
a non-Python question: you will have to research how this is done in
Windows in general, then come back here with the results of that research
and ask how to duplicate it in Python.  That part is easy, but the research
is your job.

Note that "background" and "primary task" have little meaning here... 
there is no "primary task" under Windows, although there is the concept
of the active window (the top-most one generally).  You're probably asking
for a way of "hooking" in to the OS itself, in the same way that something
like Explorer intercepts Alt-Tab no matter where it's typed...

-Peter




More information about the Python-list mailing list