Nidrax
Nidrax

Reputation: 370

Cursor leaves window when typing (ncurses)

I am using ncurses to make a simple TUI for my application. I got the basics of creating and printing to a window, but I have problems with input.

When I finish writing, the cursor is positioned at the end of the string I wrote enter image description here

But when I start typing, cursor moves to the top-left corner of terminal window.

enter image description here

How can I keep it in place while typing?

Here's my code:

#include <ncurses.h>

WINDOW *win;
int startx, starty, width, height;
int cport;


WINDOW *makewin(int h, int w, int y, int x)
{
    WINDOW *lwin;

    lwin = newwin(h, w, y, x);
    box(lwin, 0 , 0);
    wrefresh(lwin);

    return lwin;
}

void dewin(WINDOW *lwin)
{
    wborder(lwin, ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
    wrefresh(lwin);
    delwin(lwin);
}

void getPort(){
    win = makewin(height, width, starty, startx);
    wbkgd(win, COLOR_PAIR(1));
    mvwprintw(win, 0, 8, "Port Settings");
    mvwprintw(win, 2, 4, "Set port server should");
    mvwprintw(win, 3, 4, "listen to: ");
    wrefresh(win);

    scanw("%d", &cport);
}

int main()
{
    initscr();
    cbreak();
    keypad(stdscr, TRUE);


        start_color();

        init_pair(1,COLOR_WHITE, COLOR_BLACK);
        init_pair(2,COLOR_WHITE, COLOR_BLUE);
        bkgd(COLOR_PAIR(2));
        refresh();

        height = 6;
        width = 30;
        starty = (LINES - height) / 2;
        startx = (COLS - width) / 2;

        getPort();


    getch();

    dewin(win);
    endwin();
    return 0;
}

Upvotes: 2

Views: 855

Answers (2)

Aarian P. Aleahmad
Aarian P. Aleahmad

Reputation: 436

It's because you're using scanw(...) function which ultimately acts like wscanw(stdscr, ...) which gets input from stdscr. Use wscanw function to solve the problem.

Upvotes: 0

Thomas Dickey
Thomas Dickey

Reputation: 54505

scanw (and wscanw) ultimately call wgetch, which refreshes the window given as its parameter:

If the window is not a pad, and it has been moved or modified since the last call to wrefresh, wrefresh will be called before another character is read.

That is, any pending changes (including the erasure due to initscr) for stdscr would be applied by a plain scanw. The cursor will be left at the current position in the window where the program asks for input.

Upvotes: 1

Related Questions