_getch() and Ctrl-C

Martin Lafferty 1 Reputation point
2021-06-12T00:39:14.623+00:00

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.

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,419 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,526 questions
{count} votes

3 answers

Sort by: Most helpful
  1. RLWA32 40,286 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.

    105053-rawmode.png

    0 comments No comments

  2. 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!

    0 comments No comments

  3. RLWA32 40,286 Reputation points
    2021-06-14T19:05:23.333+00:00

    @Martin Lafferty Use Ctrl+Break instead.

    0 comments No comments