This code snippet was originally created as a part of an in-game console. All it does is take key press events and either adds them to a string or otherwise manipulates it. This string can be retrieved at any time. It is currently setup for the use with OIS, however this could be easily changed.
Table of contents
Usage:
Define an instance any way you like:
Copy to clipboard
EditString myEdit;
In an OIS keyboard listener:
Copy to clipboard
if( myEdit.injectKeyPress( arg ) == false ) { // Did not use the key. ... } else { // Used the key so the string has possibly changed. myTextBoxOverlayElement->SetCaption( myEdit.getText() ); ... // Display cursor somehow. Left as an exercise for the reader as // I havn't figured out how I'm going to do it yet. :) }
The Code
EditString.h
Copy to clipboard
#pragma once #include <string> #define OIS_DYNAMIC_LIB #include <OIS/OIS.h> class EditString { public: EditString(void) : mInsert(true), mPosition(mText.begin()), mCaret(0) {} EditString( std::string newText ) { setText( newText ); } ~EditString(void) {} protected: // The text for editing std::string mText; // Overwrite or insert bool mInsert; // Position for insert / overwrite std::string::iterator mPosition; // Caret Position - for positioning the cursor. int mCaret; public: void setText( std::string & newText ) { mText = newText; mPosition = mText.end(); mCaret = (int)mText.length(); } std::string & getText() { return mText; } void clear() { mText.clear() mPosition = mText.end(); mCaret = 0; } bool inserting() { return mInsert; } bool injectKeyPress( const OIS::KeyEvent ); // gets the current position in the text for cursor placement int getPosition(void) { return mCaret; } };
EditString.cpp
Copy to clipboard
#include "editstring.h" // Process a key press. Return true if it was used. bool EditString::injectKeyPress( const OIS::KeyEvent arg ) { bool keyUsed = true; if( isgraph( arg.text ) || isspace( arg.text ) ) { if( mInsert || mPosition == mText.end() ) { mPosition = mText.insert( mPosition, arg.text ); } else { *mPosition = arg.text; } mPosition++; mCaret++; } else { switch( arg.key ) { case OIS::KC_BACK: if( mPosition != mText.begin() ) { mPosition = mText.erase( --mPosition ); --mCaret; } break; case OIS::KC_INSERT: mInsert = ! mInsert; break; case OIS::KC_HOME: mPosition = mText.begin(); mCaret = 0; break; case OIS::KC_END: mPosition = mText.end(); mCaret = (int)mText.length(); break; case OIS::KC_LEFT: if( mPosition != mText.begin() ) { mPosition--; mCaret--; } break; case OIS::KC_RIGHT: if( mPosition != mText.end() ) { mPosition++; mCaret++; } break; case OIS::KC_DELETE: if( mPosition != mText.end() ) mPosition = mText.erase( mPosition ); break; default: keyUsed = false; break; } } return keyUsed; }