0

I wrote a program that catches pressed keys with getchar() and outputs the symbol and its code to the screen. I also clear the screen and hide cursor while program is working, disable echo on start and restore terminal settings as Ctrl+C pressed.

In linux everything works well, but I can't get how can I make this program work in Windows. First, commands like "\033[?2J" don't work at all. Second, I can't event disable buffered input.

Maybe someone knows how to deal with it?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <stdbool.h>
#include <signal.h>

void setBufferedInput(bool enable) {
    static bool enabled = true;
    static struct termios old;
    struct termios new;

    if (enable && !enabled) {
        tcsetattr(STDIN_FILENO,TCSANOW,&old);
        enabled = true;
    } else if (!enable && enabled) {
        tcgetattr(STDIN_FILENO,&new);
        old = new;
        new.c_lflag &=(~ICANON & ~ECHO);
        tcsetattr(STDIN_FILENO,TCSANOW,&new);
        enabled = false;
    }
}

void signal_callback_handler(int signum) {
    printf("TERMINATED \n");
    setBufferedInput(true);
    printf("\033[?25h\033[m");
    exit(signum);
}

int main() {
    char c;
    printf("\033[?25l\033[2J"); // hide the cursor; clear the screen

    // register signal handler for when ctrl-c is pressed
    signal(SIGINT, signal_callback_handler);
    setBufferedInput(false);
    while (true) {
        c=getchar();
        printf("%c %d \n",c,c); 
    }
}
Dmitry Samoylov
  • 1,228
  • 3
  • 17
  • 27
  • Its complicated: https://stackoverflow.com/questions/933745/what-is-the-windows-equivalent-to-the-capabilities-defined-in-sys-select-h-and-t – jamieguinan Jan 28 '20 at 16:43
  • 1
    But you might be able to do something simple with this: https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences – jamieguinan Jan 28 '20 at 16:44
  • 1
    Start here - https://learn.microsoft.com/en-us/windows/console/console-reference Windows console handling is completely different. – cup Jan 28 '20 at 16:57
  • @jamieguinan thanks for example. It is REALLY complicated though. – Dmitry Samoylov Jan 28 '20 at 17:42
  • Personally I'd just #ifdef the code and use the console reference code that @cup and I linked, for Windows. – jamieguinan Jan 28 '20 at 17:49

0 Answers0