Reading Keyboard Scan Codes

Peter Hansen peter at engcorp.com
Thu Jul 24 09:15:00 EDT 2003


Francois Pinard wrote:
> 
> [François Pinard]
> 
> > [...] I do not know if reading scan codes or key codes is easily done
> > within X, nor on MS-Windows.  I would like finding or discovering recipes
> > in this area.  So, please share your tricks in this area, if any! :-)
> 
> [Bjorn Pettersen]
> 
> > I'm assuming you can use the msvcrt module:
> 
> > >>> def getch():
> > ...     import msvcrt
> > ...     while not msvcrt.kbhit(): pass
> > ...     return msvcrt.getch()
> > ...
> > >>> getch()
> > 'a'
> > >>>
> 
> This does not give scan codes (or key codes of some sort).  I would like
> being able to detect, for example, if Ctrl is being held while Keypad-5
> is entered, or any other such (possibly unusual) combination of keys.

I'm not sure about your specific case with Ctrl-Keypad-5 (is that a valid
combination?), but the above will return 0 or 224 plus another code for the 
special keys (such as function keys, and the numeric keypad keys, and
those values are different when Ctrl is held down.

For example, Home on the numeric keypad is (0, 71), while Ctrl-Home
is (0, 119).  The other Home key comes back as (224, 71), and with
Ctrl it is (224, 119).

Experiment a bit and you'll figure it out.

-Peter




More information about the Python-list mailing list