View Full Version : C++ Key Press Check

10-15-2008, 05:05 AM
How would I go about making a program that closes or carries out a function when the user presses the appropriate (or any) key? Such as:

if(key_press) {
// do this

ralph l mayo
10-15-2008, 08:59 AM
The answer is platform-dependent. If you can live with having to press return after the key you can use std::cin.get(), but if not you'll have to resort to a native API or compiler feature to get the key in real-time.

getch() is a common non-portable way to grab a key, and if you're programming for Windows you just need to look for the appropriate notification in your event loop (WM_KEYDOWN?)

edit: cin.get() and getch() are synchronous, the notification isn't... you'll probably need to spawn a thread to look for the keypress with the synchronous methods if it's important that the input not block other stuff.

10-15-2008, 09:00 AM
Google gives http://www.fedoraforum.org/forum/showthread.php?page=1&t=147415, which may help you.