Fred Staff
Posts : 33 Join date : 2010-05-27 Age : 31 Location : Oklahoma
| Subject: Filter MS-Windows Console Input Keys - C++ Thu Jun 03, 2010 5:09 pm | | | IntroductionToday I will show you guys a source code for you C++ users. This program could be either C or C++, the difference is only one line of code in main().The code snippet shows how to accept only numeric keys from the keyboard, ignoring all others. You could use this as the basis for filtering other types of keyboard input. There are two functions: getkey() just returns a numeric digit 0-9 as well as '-' (for negative values), '.' for floating point values, and '\n'. This function returns 0 for all other keys. getnumber() repeatedly calls getkey() until the Enter key is pressed and builds an integer value. main() just merely displays the value returned by getnumber(). Well here is the snippet: - Code:
-
#include <windows.h> #include <iostream>
int getkey() { bool rvalue = false; const int MaxEvents = 16; // Get handle to stdin used by console functions HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD dwNumRead = 0; DWORD dwNumEvents = 0; INPUT_RECORD buf[MaxEvents];
// get number of available keyboard events if( GetNumberOfConsoleInputEvents(hStdin, &dwNumEvents) ) { if( dwNumEvents > 0) { memset(buf, 0, sizeof(buf)); // Get the number of events available at the console if( ReadConsoleInput(hStdin,buf,MaxEvents, &dwNumRead) ) { // process each event for(DWORD i = 0; i < dwNumRead; i++) { // if keyboard event if( buf[i].EventType == KEY_EVENT) { KEY_EVENT_RECORD* pKey = (KEY_EVENT_RECORD*)&buf[i].Event.KeyEvent; // if key down event if( pKey->bKeyDown == TRUE) { // test the key type. This will accept all numeric // digits 0-9 as well as - and . keys if( isdigit(pKey->uChar.AsciiChar) || pKey->uChar.AsciiChar == '-' || pKey->uChar.AsciiChar == '.') { return pKey->uChar.AsciiChar; } else if( pKey->wVirtualKeyCode == VK_RETURN) return VK_RETURN; } } } } } } return 0; }
int getnumber() // returns an integer { int number = 0; int key = 0; int keycount = 0; bool isnegative = false; // while key is not pressed while( key != VK_RETURN ) { // wait for key press, you could do // something else here while( (key = getkey()) == 0) Sleep(100);
if( key != VK_RETURN) { // make the final result negative if( key == '-' ) { // only allowed as first key stroke if( keycount == 0) isnegative = true; } // ignore floating point else if( key == '.' ) { ; // ignore it } else { // convert ascii digit to binary and shift // into the number. This might appear to be a // little awkward here, but it's checking for // numeric overflow. int n = key - '0'; int k = number * 10 + n; if( k > number ) // check for numeric overflow number = k; } } ++keycount; } if( isnegative ) number = -number; return number; }
int main() { int n = getnumber(); std::cout << "n = " << n << '\n'; }
This shows how to filter keys in an MS-Windows console program without actually echoing the keys on the console window. |
|