Using backspace with ncurses

时光毁灭记忆、已成空白 提交于 2019-12-21 16:59:54

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11387572/using-backspace-with-ncurses

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!