'How to trigger a function when control c is pressed in c++

I'm wondering how could I trigger a function when control + c is pressed but I want it not only in the program window but outside the window like in a browser, text pad and etc. Help would be appreciated. This would be in C++ Thanks

c++


Solution 1:[1]

You can do something like this on Windows:

char input = _getch();
    
if (input == '\x3')
{
    std::cout << "Ctrl C pressed!" << std::endl;
    //...
}

The above code will print "Ctrl C pressed!" when input == '\x3' (Control C).

Full example:

#include <iostream>
#include <conio.h>

void foo(char character)
{
    std::cout << character << std::endl;
}

int main()
{
    while (true)
    {
        char input = _getch();

        if (input == '\x3')
        {
            foo(input);
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1