Search code examples
ncurseszig

ncurses: program exiting when arrow key pressed


my question is exactly as the title says. My program exits right after I press an arrow up.

Here's my program:

pub fn main() !void {
    _ = c.initscr();
    defer _ = c.endwin();

    var i: u32 = 0;
    main_loop: while (true) : (i += 1) {
        var key: c_int = undefined;
        if (i != 0) {
            key = c.getch();

            switch (key) {
                std.ascii.control_code.esc => break :main_loop,
                c.KEY_UP => {
                    const dir = try std.fs.cwd().openIterableDir(cwd_path, .{});
                    _ = dir;
                    try putText(CWD_Y + 2, CWD_X + 2, "hahaha");
                },
                else => try putText(ERROR_Y, ERROR_X, "ERROR: pressed unhandled key"),
            }
        }

        try updateCwd();
        try putText(CWD_Y, CWD_X, cwd_path);
    }
}

Thanks


Solution

  • On most terminals, KEY_UP corresponds to an escape sequence. If you want your program to translate that escape sequence into a key-code, use the keypad function, e.g., calling this after initscr:

    c.keypad(1);