I had a little password input routine that I converted over to getch( ) and getche( ). getche( ) is the same except with character echo to screen. I guess it's similar to what's already posted but then again I guess it should be. It easy to modify by expanding or limiting input around isprint(...); It's been so long since I used Turbo C++ getch( ) that I don't actually remember what key-presses should be responded to.
Regards,
Brian
Code:
char getch(void)
{
DWORD dwCharsRead;
INPUT_RECORD inRec;
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
while(ReadConsoleInput(hInput, &inRec, 1, &dwCharsRead))
if(inRec.EventType == KEY_EVENT && inRec.Event.KeyEvent.bKeyDown
&& isprint(inRec.Event.KeyEvent.uChar.AsciiChar))
return(inRec.Event.KeyEvent.uChar.AsciiChar);
return('ì'); // dummy return to suppress warning msg.
}
Code:
char getche(void)
{
INPUT_RECORD inRec;
char buffer[2] = {'\0'};
DWORD dwCharsRead, dwCharsWritten;
HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
while(ReadConsoleInput(hInput, &inRec, 1, &dwCharsRead))
if(inRec.EventType == KEY_EVENT && inRec.Event.KeyEvent.bKeyDown
&& isprint(inRec.Event.KeyEvent.uChar.AsciiChar))
{
buffer[0] = inRec.Event.KeyEvent.uChar.AsciiChar;
WriteConsole(hOutput, buffer, 1, &dwCharsWritten, NULL);
return(inRec.Event.KeyEvent.uChar.AsciiChar);
}
return('ì'); // dummy return to suppress warning msg.
}
Code:
#include <windows.h>
#include <iostream>
#include <cstdlib>
using namespace std;
/* Password function for Win32 console
* reads keystrokes but displays * to mask printable entries
* first parameter: a pointer to a char array, buffer to hold password
* second parameter: password buffer size, including null terminator
* return value: funtion returns 1 if max buffer is reached, else returns 0
*/
int Password( char * buffer, int buffSize)
{
int count = 0;
INPUT_RECORD inRec;
HANDLE hInput, hOutput;
DWORD dwCharsRead, dwCharsWritten;
buffSize--;
hInput = GetStdHandle(STD_INPUT_HANDLE);
hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
while(ReadConsoleInput(hInput, &inRec, 1, &dwCharsRead) && count < buffSize)
if(inRec.EventType == KEY_EVENT && inRec.Event.KeyEvent.bKeyDown == TRUE)
if(isprint(inRec.Event.KeyEvent.uChar.AsciiChar))
buffer[count++] = inRec.Event.KeyEvent.uChar.AsciiChar,
WriteConsole(hOutput, "*", 1, &dwCharsWritten, NULL);
else
if(inRec.Event.KeyEvent.uChar.AsciiChar == '\b' && count > 0)
WriteConsole(hOutput, "\b \b", 3, &dwCharsWritten, NULL),
count--;
else
if(inRec.Event.KeyEvent.uChar.AsciiChar == '\r')
break;
buffer[count] = '\0';
if(count == buffSize)
return(1);
else
return(0);
}
int main( int argc, char * argv[] )
{
char buffer[256];
cout << endl << endl << "Enter Password: ";
Password(buffer, 256);
return(0);
}