summaryrefslogtreecommitdiff
path: root/key.cpp
blob: 871dbdb55c8635a8a7cebd151770c35901114111 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <termios.h>
#include <unistd.h>
#include <escape.ansi>
// useless btw, just use xev if you actually need this, just made for fun
char getch() {
    struct termios oldt, newt;
    char ch;
    tcgetattr(STDIN_FILENO, &oldt); // Get the current terminal settings
    newt = oldt;                     // Copy the settings
    newt.c_lflag &= ~(ICANON | ECHO); // Disable canonical mode and echo
    tcsetattr(STDIN_FILENO, TCSANOW, &newt); // Set the new settings
    ch = getchar();                  // Read a character
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt); // Restore the old settings
    return ch;
}

int main() {
    std::cout << "Press " << red << "any key" << def << " to see its ASCII keycode. | Press " << red << "ESC" << def << " to exit." << std::endl;

    while (true) {
        char ch = getch(); // Get a character from the user

        // Check for ESC key to exit
        if (ch == 27) { // ASCII code for ESC
        	std::cout << "ESC = 27\n" << red << "Quitting ..\n" << def;
			break;
        }
		
		if (ch == 32) {
			std::cout << "SPACEBAR = " << static_cast<int>(ch) << std::endl;
		} else if (ch == 9) {
			std::cout << "TAB = " << static_cast<int>(ch) << std::endl;
		} else if (ch == 127) {
			std::cout << "BACKSPACE = " << static_cast<int>(ch) << std::endl;
		} else if (ch == 10) {
			std::cout << "ENTER = " << static_cast<int>(ch) << std::endl;
		} else {
			// Output pressed key
       		std::cout << ch << " = " << static_cast<int>(ch) << std::endl;
		}
    }

    return 0;
}