Archived:How to detect key presses in PySymbian
This code snippet demonstrates how to detect key presses using the PySymbian keycapture module. Describing how to use the bind method of various UI controls is beyond the scope of this article; the PySymbian documentation or other material should be consulted for details on this matter.
Note: The keycapture module requres the SwEvent capability in S60 3rd Edition and later devices.
It should be noted that not all keys can be captured (for example, the multimedia menu key on the Nokia N95 and Nokia N95 8GB). Furthermore, although using this method to capture key events generally cancels the action that would normally be performed when that key would be pressed, some keys are impossible to override (for example, the menu key and hand-up key); in other words, it is impossible to prevent their standard action from taking place.
import keycapture, key_codes, globalui
#Define a method to be called when a key press event occurs
#TODO: Handle events here
#For example, tell the user what key was pressed
for i in dir(key_codes):
if key == getattr(key_codes, i):
#Make the application close when the right softkey is pressed
if key == key_codes.EKeyRightSoftkey:
#Create a KeyCapturer object, specifying the method
capturer = keycapture.KeyCapturer(cb_key_capture)
#All keys should be captured
capturer.keys = keycapture.all_keys
#Alternatively, if only certain keys need to be handled, they can be specified as a tuple of keycodes
#Start detecting key presses
Key presses are detected and the user is notified accordingly.