keyboard interrupt routine visual studio C++ console app

498 Views Asked by At

I am using VS 2022 Preview to write a C++ console application. I wish to detect a keyboard hit and have my interrupt handler function called. I want the key press detected quickly in case main is in a long loop and therefore not using kbhit().

I found signal() but the debugger stops when the Control-C is detected. Maybe it is a peculiarity of the IDE. Is there a function or system call that I should use?

Edit: I am vaguely aware of threads. Could I spawn a thread that just watches kbd and then have it raise(?) an interrupt when a key is pressed?

1

There are 1 best solutions below

1
MaryK On

I was able to do it by adding a thread. On the target I will have real interrupts to trigger my ISR but this is close enough for algorithm development. It seemed that terminating the thread was more trouble than it was worth so I rationalized that I am simulating an embedded system that does not need fancy shutdowns.

I decided to just accept one character at a time in the phony ISR then I can buffer them and wait and process the whole string when I see a CR, a simple minded command line processor.

// Scheduler.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <Windows.h>
#include <iostream>
#include <thread>
#include <conio.h>

void phonyISR(int tbd)
{
    char c;
    while (1)
    {
        std::cout << "\nphonyISR() waiting for kbd input:";
        c = _getch();
        std::cout << "\nGot >" << c << "<";
    }
}

int main(int argc, char* argv[])
{
    int tbd;
    std::thread t = std::thread(phonyISR, tbd);

    // Main thread doing its stuff
    int i = 0;
    while (1)
    {
        Sleep(2000);
        std::cout << "\nMain: " << i++;
    }

    return 0;
}