Join Now
Quality Rating:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)
Expertise Level:
  • Currently 0.0 / 5
(0.0 / 5 - 0 votes cast)

This page was last modified 22:19, 2 August 2007.

Simple keyboard wrapper for games

From Forum Nokia Wiki


This article presents a simple class to handle keyboard input in a game-like way.


Class declaration

// INCLUDES
#include <e32keys.h>
#include <e32std.h>
 
// CLASSES
 
/**
 * A simple keyboard wrapper.
 */
class TKeyboardWrapper
{
  public:
	
    // key codes not found in header files
    enum TKeys {
		EKey0 = 48,
		EKey1,
		EKey2,
		EKey3,
		EKey4,
		EKey5,
		EKey6,
		EKey7,
		EKey8,
		EKey9,
		EKeyShift = 127,
		EKeyStar  = 133			
		};
 
  public:
	
  /**
   * Default constructor.
   */
  TKeyboardWrapper ()
  { Clear (); }
		
		
  /**
   * Clears key state.
   */
  void Clear ()
  { Mem::FillZ (iKeys, 256); }
		 
		 
  /**
   * Asks if some key is down.
   */
  TBool IsKeyDown (TInt aKey) const
  { ASSERT (aKey >= 0 && aKey < 256); return iKeys [aKey]; }
		 
		
  /**
   * Sets a key as down.
   */
  void SetKey (TInt aKey)
  { ASSERT (aKey >= 0 && aKey < 256); iKeys [aKey] = ETrue; }
		 
		
  /**
   * Sets a key as up.
   */
  void ClearKey (TInt aKey)
  { ASSERT (aKey >= 0 && aKey < 256); iKeys [aKey] = EFalse; }
		 
		
  /** 
   * Check if any key is down.
   */
  TBool AnyKeyDown () const
  {
    for (TInt16 i = 0; i < 256; ++i)
     {
       if (iKeys [i])
	return true;
     }
			
    return false;
  }
 
  private:
    TBool iKeys [256];
};

Usage

It is necessary to collect the keyboard data in some of the methods that receive keyboard input. For example, using the HandleKeyEventL() of the Application UI class:

TKeyResponse CMyAppUi::HandleKeyEventL (const TKeyEvent& aKeyEvent, TEventCode aType)
{	
	if (aType == EEventKeyDown)
	 iKeyboard.SetKey (aKeyEvent.iScanCode);
	else
	if (aType == EEventKeyUp)
	 iKeyboard.ClearKey (aKeyEvent.iScanCode);
 
	return EKeyWasConsumed;
}

In the example, iKeyboard is a TKeyboardWrapper instance. Later, to get the key state it is necessary to use the constants defined in the TStdScanCode enum (e32keys.h). Example:

void CMyAppUi::ProcessInput ()
{
  if (iKeyboard [EStdKeyLeftArrow] )
    // left arrow is down
 
  if (iKeyboard [TKeyboardWrapper::EKey0] )
    // 0 key is down
 
}

It is important not to use the constants defined in the TKeyCode enum, because their use leads to incorrect behavior and possibly to an invalid array access.

Related Discussions
Thread Thread Starter Forum Replies Last Post
How To Emulate keystrokes wagonli Symbian User Interface 4 2007-03-14 10:35
Nokia-MIDlet-Category problem chadwickdonald Mobile Java General 3 2004-11-02 08:34
Problems with a python wrapper: convert PyObject to Image pdcb_pdcb Python 6 2008-03-21 22:57
minimising my application giridharn General Symbian C++ 2 2005-05-11 11:26
Hosting java games smb101 Mobile Java General 7 2004-09-21 01:30
 
Powered by MediaWiki