question

MartinLafferty-2003 avatar image
0 Votes"
MartinLafferty-2003 asked RLWA32-6355 answered

_getch() and Ctrl-C

The documentation for _getch() is very clear:

https://docs.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.

windows-apic++
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

FWIW, I get the same result as you, so on the face of it, that documentation would appear to be incorrect.

0 Votes 0 ·
RLWA32-6355 avatar image
0 Votes"
RLWA32-6355 answered

I agree with @DavidLowndes-6766 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.

105053-rawmode.png



rawmode.png (9.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MartinLafferty-2003 avatar image
0 Votes"
MartinLafferty-2003 answered

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!

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RLWA32-6355 avatar image
0 Votes"
RLWA32-6355 answered

@MartinLafferty-2003 Use Ctrl+Break instead.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.