简体   繁体   中英

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.

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.

i have solution in c / c++ both

inline void signal_callback_handler(int signum){signal(SIGINT, signal_callback_handler);} put this as global

make a call below in main() signal(SIGINT, signal_callback_handler);

don't forget to include stdio.h and signal.h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM