Saturday 24 August 2013

Keyboard Navigating DOS Shell Style

Sometimes you might want to break out of the old "Enter number to change...", "Enter item to delete...".

This program demonstrates creation of a menu that can be navigated with the arrow keys, somewhat similar to THIS.
You can delete an item if user presses "Delete" (595), edit it if user hits "Enter" (13). No, no it doesn't work in this program, just saying :P

This program requires that you have the myconstdwin.h header file.

User enters three names (Which would have been four, but Kenny is poor), and then any one may be highlighted using the arrow keys.

SAMPLE:


CODE:

#include <myconstdwin.h>

void hl(int y);
void dl(int y);

char names[3][20];

void main()
{
    int loop,y,key;
    for(loop=0;loop<3;loop++)
    {
        printf("Enter name %i: ",loop+1);
        gets(names[loop]);
        printf("%s\n",names[loop]);
    }

    system("cls");
    gotoxy(0,5);
    printf("press UP or Down to navigate, or Esc to exit\n");

    gotoxy(0,0);
    for(loop=0;loop<3;loop++)
    {
        printf("Name #%i: %s\n",loop+1,names[loop]);
    }

    y=1;
    for(;;)
    {
        hl(y);
        key=get_key();
        if(key==592) //down
        {
            if(y==1 || y==2)
            {
                dl(y);
                y++;
                hl(y);
            }
            else
            {
                dl(y);
                y=1;
                hl(y);
            }
        }
        else if(key==584) //up
        {
            if(y==2 || y==3)
            {
                dl(y);
                y--;
                hl(y);
            }
            else
            {
                dl(y);
                y=3;
                hl(y);
            }
        }
        else if(key==27) //ESC
        {
            system("cls");
            break;
        }
    }
}

void hl(int y)
{
    gotoxy(0,y-1);
    SetColorAndBackground(15,9);
    printf("Name #%i: %s\n",y,names[y-1]);
    SetColorAndBackground(8,0);
}
void dl(int y)
{
    gotoxy(0,y-1);
    printf("                                   ");
    gotoxy(0,y-1);
    printf("Name #%i: %s\n",y,names[y-1]);
}

int get_key()
{
    int c = getch();
    switch (c)
    {
      case 0:   return getch()+256;
      case 224: return getch()+512;
    }
    return c;
}

No comments:

Post a Comment