@Martin Lafferty Use Ctrl+Break instead.
_getch() and Ctrl-C
The documentation for _getch() is very clear:
https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=msvc-160
"None of these functions can be used to read CTRL+C"
However this does not seem to be true in the most trivial case.
#include <iostream>
#include <conio.h>
#include <windows.h>
int main()
{
std::cout << "x to exit\n";
while (true) {
int c = _getch();
std::cout << "KB " << c << '\n';
if (c == 'x')
return 0;
}
return 0;
}
Run this program and it writes "KB 3" for Ctrl-C.
If I don't call _getch() then Ctrl-C is handled as expected.
3 answers
Sort by: Newest
-
-
Martin Lafferty 1 Reputation point
2021-06-14T18:59:42.093+00:00 Thanks, that's interesting. This is a bit annoying if you are relying on Ctrl-C to call the signal handler. I don't suppose there is any way around this given that the RTL resets the mode. The first thing I did when I found this was check that ENABLE_PROCESSED_INPUT was set in console mode. It did not occur to me that _getch would be so brutal as to reset the lot!
-
RLWA32 40,651 Reputation points
2021-06-12T15:04:07.64+00:00 I agree with @David Lowndes about the docs appearing to be incorrect.
Inside the code for the _getch function the console mode is reset to allow Ctrl+C to be read as input.