C++ Method of detecting whether a key on a keyboard is pressed
- 2020-06-07 04:58:08
- OfStack
The detection keyboard is similar to the mouse, but it is easier to remember
But it's kind of weird, like if you want to detect a letter, it has to be in uppercase
Specific reference to the virtual keyboard value table, baidu can be searched
I made up a little program to make it clear
#include<iostream>
#include<windows.h>
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0) // It's necessary. I learned it by heart
using namespace std;
void color(int a){// Change the color of the output than system("color x") Much faster
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);
/*
<span style="white-space:pre"> </span> word
1 Dark blue
2 Dark green,
3 Deep blue
4 Deep red
5 Deep pink
6 yellow
7 Deep white
8 gray
9 The light blue
10 Light green
11 Shallow blue
12 Light red
13 Pale pink
14 Light yellow
15 Light white
background
1~15 black
16~31 Dark blue
32~47 Dark green,
48~63 Deep blue
64~79 Deep red
80~95 Deep pink
96~111 Dark yellow
112~127 Deep white
128~143 gray
144~159 The light blue
160~175 Light green
176~191 Shallow blue
192~207 Light red
208~223 Pale pink
224~239 Light yellow
240~255 Light white
*/
}
void check(char c){// Detect if a key is pressed, and press it to change the output color
if(!KEY_DOWN(c))color(7);
else color(112);
printf(" %c ",c);
color(7);
}
int main(){
while(1){
check('Q');check('W');check('E');check('R');check('T');check('Y');check('U');check('I');check('O');check('P');
printf("\n\n ");
check('A');check('S');check('D');check('F');check('G');check('H');check('J');check('K');check('L');
printf("\n\n ");
check('Z');check('X');check('C');check('V');check('B');check('N');check('M');
Sleep(20);// Loop time interval to prevent too much memory
system("cls");// Clear the screen
}
return 0;
}