Gelatin
Gelatin

Reputation: 2413

How can I add new ncurses subwindows in response to user demand?

I'm trying to write an ncurses program which adds new windows in response to the user pressing keys. For example, consider the following C++ code:

#include <iostream>
#include "curses.h"

using namespace std;

int main()
{
    WINDOW * win = initscr();
    start_color();
    noecho();

    WINDOW * sub = subwin(win, 20, 20, 2, 2);
    wborder(sub, 0, 0, 0, 0, 0, 0, 0, 0);

    keypad(win, TRUE);

    while (true)
    {
        int c = wgetch(win);

        if (c == KEY_DOWN)
        {
            WINDOW* box = subwin(sub, 2, 2, (rand() % 20) + 2, (rand() % 20) + 2);
            wborder(box, 0, 0, 0, 0, 0, 0, 0, 0);
        }
        else if (c == KEY_UP)
        {
            wrefresh(sub);
        }
    }

    endwin();

    return 0;
}

The user can press the down key to create new windows as many times as they want, but wrefresh will only draw them once. This appears to be related to the call to wgetch, a program that doesn't respond to keys works fine. Calling refresh also causes the problem.

Upvotes: 2

Views: 2586

Answers (1)

parkydr
parkydr

Reputation: 7784

The subwin man page says:

When using this routine, it is necessary to call touchwin or touchline on orig before calling wrefresh on the subwindow.

Creating a sub-window does not actually change the parent window, so after the first refresh the parent window has not changed, touching the window marks it as changed.

So change:

wrefresh(sub);

to

touchwin(sub);
wrefresh(sub);

Upvotes: 1

Related Questions