cplusplus
.com
TUTORIALS
REFERENCE
ARTICLES
FORUM
C++
Tutorials
Reference
Articles
Forum
Forum
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Lounge
Jobs
Forum
Beginners
How to make a program do something by pr
How to make a program do something by pressing a key on the keyboard
Mar 14, 2016 at 2:16pm UTC
gameguy8888
(13)
Let's say I made a program which would display "Hi" when I hit the 'a' key.
what line of code should I use to do that? and please explain the concept, thanks :)
Mar 14, 2016 at 3:07pm UTC
InsanelyNormal
(26)
You could use GetAsyncKeyState, from <windows.h>, to detect the key as long as it is pressed: It will spam Hi as long as you hold the 'a' key.
Otherwise (also simpler) use getch() in a loop and check the value.
1
2
3
4
5
6
7
while
(1) {
if
(getch() ==
'a'
) { cout<<
"Hi!"
<<endl; } }
Explanation: Getch() return a key pressed unde char format, and pauses the program when it is called untill a key is pressed.
By checking if the value returned is a specific char (getch()=='a'), you can test for a simple keypress.
Topic archived. No new replies allowed.