cubuntuterminalncursessignal-handling

Ncurses: Detecting if F1 key pressed and using signals


i am trying to learn ncurses library and i came up with code below:

#include <ncurses.h>
#include <stdlib.h>
#include <signal.h>

static void finish(int sig);

int main(int argc, char** argv) {

    char c;
    initscr();
    raw();
    keypad(stdscr, TRUE);
    noecho();

    (void) signal(SIGINT, finish);      /* arrange interrupts to terminate */

    printw("Type any character to see it in bold:\n");
    refresh();
    c = getch();

    /* work around for ctrl+c */
    if(c == 3)
        finish(0);

    while(c != KEY_F(1))
    {
        printw("The pressed key is ");
        attron(A_BOLD);
        printw("%c\n", c);
        attroff(A_BOLD);
        refresh();
        c = getch();

        /* work around for ctrl+c */
        if(c == 3)
            finish(0);

        printf("Code = %d\n", c);
    }

    printw("F1 key pressed.\n");
    endwin();

    return (EXIT_SUCCESS);
}

static void finish(int sig)
{
    endwin();

    /* do your non-curses wrapup here */

    exit(0);
}

The problem in this code is when i press F1 key, terminal help window opens and i can't catch F1 key press. Also i can't catch ctrl+c press by signal mechanism. Is there any way to override F1 key on terminal and how can i use signals in curses mode.


Solution

  • In the terminal window's menu bar, Edit -> Preferences. Go to the Shortcuts tab. Clear the conflicting shortcuts.

    Better yet, don't use any shortcuts that conflict with the terminal emulator's pre-existing shortcuts.

    You should probably leave SIGINT alone. ncurses already intercepts it to clean up the terminal before exit. If you need to run some cleanup code of your own, try the atexit function.