I have a simple ncurses program set up that reads characters one at a time with getch() and copies them into a buffer. The issue I am having is detecting a press of the backspace key. Here is the relevant code:
while((buffer[i] = c = getch()) != EOF) {
++i;
if (c == '\n') {
break;
}
else if (c == KEY_BACKSPACE || c == KEY_DC || c == 127) {
i--;
delch();
buffer[i] = 0;
}
refresh();
}
But when attempting to run this code, this is what appears on the screen after trying to delete characters from the line "this is a test":
this is a test^?^?^?
and the contents of buffer
are:
this is a test
With gdb I know that the if statement checking for a delete/backspace is being called, so what else should I be doing so that I can delete characters?
It looks like ^?
is what's echoed to the screen when you enter a DEL character.
You could probably call delch()
twice, but then you'd have to figure out which characters echo as two-character (or more) sequences.
Your best bet is probably to call noecho()
and explicitly print the characters yourself.
There's actually a simpler way of doing it, check this code out:
while((ch = getch() != KEY_F(1))
{
switch(ch)
{
case 127: { // Delete key
form_driver(Form, REQ_DEL_PREV);
break;
}
case 10: {// Enter key
// Do something
}
default: {
// If this is a normal character
}
}
}
(In this example, I am requesting the Form driver to delete the last typed character in the form "Form" this emulates the regular function of the delete key exactly.)
Note: On my machine (Mac OS) this works. What number represents each key may vary on your computer. You can write a program like this though to find out what keycode you need to use though:
printw("Press Delete and its corresponding keycode will be printed!");
while((ch = getch() != KEY_F(1))
{
printw(ch);
}
Hope this helps anybody, I think it really simplifies an otherwise complicated program.