How to detect that a key is being pressed, not HAS been pressed earlier!??

Sean Richards somebody at nowhere.com
Wed Jan 28 21:37:51 CET 2004


runed at stud.cs.uit.no (Rune) writes:

> Hey
>
> I'm trying to build a gui application and need to know if the user is
> actually holding down the shift or ctrl key. That is, if the user
> currently is holding down the shift key. In pseudo code this will boil
> down to something like this:
>
> def test:
>   if user presses shift:
>     return SHIFT_IS_PRESSED
>   elif user presses ctrl:
>     return CTRL_IS_PRESSED
>   else
>     return false
>
> It's important to notice here that I'm not interested if the user has
> already pressed shift or ctrl. I'm only interested in knowing if he is
> currently holding down one of these keys. (I have looked into msvcrt
> and the like but have found no answer..) The function should also work
> in both windows and Linux.
>
> Any help is appriciated :)

In wxPython you could do it like this ...

1. Bind the key press events to the two functions

EVT_KEY_DOWN(self, self.OnKeyDown)
EVT_KEY_UP(self, self.OnKeyUp)

2. Set or unset a flag on keydown and keyup

def OnKeyDown(self, event):
    if (event.GetKeyCode() == WXK_SHIFT):
        self.Shift = True
    elif (event.GetKeyCode() == WXK_CONTROL):
        self.Control = True

def OnKeyUp(self, event):
    if (event.GetKeyCode() == WXK_SHIFT):
        self.Shift = False
    elif (event.GetKeyCode() == WXK_CONTROL):
        self.Control = False

Vennlig hilsen,  Sean


-- 
"Hver sin smak", sa vintapperen, han drakk mens de andre sloss.



More information about the Python-list mailing list