I use LEFT-ArrowKey and RIGHT-Arrowkey to control a commandline program from "outside". The problem: If no key is used (default), I don't get the cursor back, because endwin() doesn't return the screen before the ncurses-initialization. After the programm has finished (default-case), any kind of key must be pressed to show the screen (before ncurse was initialized) again.
I tried getchar() and there is nearly the same problem: Instead of using one (any) key to finish the program in default-case, there must be used ENTER for one time...
After endwin() the main program ends (return 0). You can do endwin() into the key-cases. Here a short complete example. You can see, why it is difficult, if you do "exit(0)" out of the code 3rd key-case...
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <string>
#include <ncurses.h>
#include <unistd.h>
#define SLEEP( milliseconds ) usleep( (unsigned long) (milliseconds * 1000.0) )
int main()
{
int ch;
initscr(); /* Start curses mode */
raw(); /* Line buffering disabled */
keypad(stdscr, TRUE); /* We get F1, F2 etc.. */
noecho(); /* Don't echo() while we do getch */
while (1)
{
SLEEP( 100 );
printw("Exit: Up arrow key\n");
ch = getch(); /* If raw() hadn't been called
* we have to press enter before it
* gets to the program */
if(ch == KEY_SRIGHT)
{
printw("Shifted right arrow key\n");
}
elseif(ch == KEY_SLEFT)
{
printw("Shifted left arrow key\n");
}
elseif(ch == KEY_UP) // Up arrow key
{
endwin(); /* End curses mode */
exit(0);
//return 0;
}
else
{ printw("The pressed key is ");
attron(A_BOLD);
printw("%c\n", ch);
attroff(A_BOLD);
}
//refresh(); /* Print it on to the real screen */
//getch(); /* Wait for user input */
}
endwin(); /* End curses mode */
exit(1);
//return 0;
}