[Tutor] [ctypes-users] Press ESC to exit()

eryk sun eryksun at gmail.com
Tue May 2 01:56:37 EDT 2017

On Tue, May 2, 2017 at 3:03 AM, Michael C
<mysecretrobotfactory at gmail.com> wrote:
> holy cow

The code for a global keyboard hook is a bit complex - mostly because
I had to use ctypes (properly instead of an unreliable hack). Normally
an application has one or more windows and a message loop, in which
case there's no need for such an awkward approach.

But you're asking to do this from a console application, which doesn't
own a window. The window procedure that gets keyboard input from the
system is in the console host process (conhost.exe). It processes
input as a sequence of events that it stores in its input buffer. Thus
you could use the input buffer instead of a global keyboard hook, but
that comes with its own set of problems. You're no longer getting
notified as soon as the character is typed in the window. Instead, the
escape-key monitor has to share the input buffer with the main

Events can be read without removing them via PeekConsoleInput, or read
and removed via ReadConsoleInput. They can also be flushed (discarded)
via FlushConsoleInputBuffer. If your script doesn't read from the
console and the escape-key monitory only peeks the input buffer, it
will grow without bound. However, it shouldn't read or flush input
events that the main task needs, and the main task shouldn't read
events that causes the escape-key monitoring thread to miss the user
pressing escape. It needs an integrated design.

More information about the Tutor mailing list