How can I make a keyboard input function that allows you to bring up the CHAR menu (or MATH, etc)?

Previous Input: Keyboard and Link Next

Q: I really need a routine like InputStr given above, but which is able to bring up the CHAR dialog. However, I am not able to make such routine by myself...
A: I received a lot of such questions. These questions are usually asked by newbie programmers, but the answer is quite advanced. Although I don't like to present advanced routines as-is without a lot of necessary explanations, I am requested to do so. Well, here is a routine (example "Input String Advanced"):
// Custom string input example enabling the CHAR menu

#define USE_TI89              // Compile for TI-89
#define USE_TI92PLUS          // Compile for TI-92 Plus
#define USE_V200              // Compile for V200

#define MIN_AMS 100           // Compile for AMS 1.00 or higher
#define SAVE_SCREEN           // Save/Restore LCD Contents

#include <tigcclib.h>         // Include All Header Files

short captured;

CALLBACK void CaptureHandler(EVENT *ev)
{
  if (ev->Type == CM_STRING)
    captured = *(ev->extra.pasteText);
}

void InputStr(char *buffer, unsigned short maxlen)
{
  SCR_STATE ss;
  short key;
  unsigned short i = 0;
  buffer[0] = 0;
  SaveScrState (&ss);
  do
    {
      MoveTo (ss.CurX, ss.CurY);
      printf ("%s_  ", buffer);
        // Note that two spaces are required only if the F_4x6 font is used
      do
        {
          key = ngetchx ();
          if (key == KEY_CHAR && i < maxlen)
            {
              EVENT ev;
              captured = 0;
              ev.Type = CM_KEYPRESS;
              ev.extra.Key.Code = key;
              EV_captureEvents (CaptureHandler);
              EV_defaultHandler (&ev);
              EV_captureEvents (NULL);
            }
        } while (!captured);
      if (key == KEY_CHAR && i < maxlen)
        buffer[i++] = captured;
      if (key >= ' ' && key <= '~' && i < maxlen) buffer[i++] = key;
      if (key == KEY_BACKSPACE && i) i--;
      buffer[i] = 0;
    } while (key != KEY_ENTER);
}

// Main Function
void _main(void)
{
  char s[20];
  clrscr ();
  InputStr (s, 20);
  printf ("\n%s", s);
  ngetchx ();
}
It will be good if you can understand how it works (I recommend reading the documentation for the events.h header file). Note that this example used to be broken in previous releases of TIGCC, as it took the address of a nested function, a GNU C Extension which didn't work correctly at that time.


See also: How can I get input from the keyboard?, Do you have the function that gets called when you do InputStr in TI-Basic?, getsn