En
meget simpel password funktion til en konsol:
#include <windows.h>
#include <stdio.h>
HANDLE StdIn, StdOut;
WORD GetChar()
{
DWORD NumEventsRead;
INPUT_RECORD InputRecord;
while(1)
{
if(!ReadConsoleInput(StdIn, &InputRecord, 1, &NumEventsRead))
return 0;
if(InputRecord.EventType & KEY_EVENT && InputRecord.Event.KeyEvent.bKeyDown)
{
if(InputRecord.Event.KeyEvent.wVirtualKeyCode != VK_CONTROL &&
InputRecord.Event.KeyEvent.wVirtualKeyCode != VK_MENU &&
InputRecord.Event.KeyEvent.wVirtualKeyCode != VK_SHIFT)
{
return InputRecord.Event.KeyEvent.wVirtualKeyCode;
}
}
}
}
void GetPass(char *aDest, size_t aMaxLen)
{
CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo;
GetConsoleScreenBufferInfo(StdOut, &ConsoleScreenBufferInfo);
size_t Pos = 0;
WORD Key;
DWORD Dummy;
while((Key = GetChar()) != VK_RETURN)
{
if(Key >= 'A' && Key <= 'Z' && Pos < aMaxLen -1)
aDest[Pos++] = (char )Key;
else if(Key == VK_BACK && Pos > 0)
{
SetConsoleCursorPosition(StdOut, ConsoleScreenBufferInfo.dwCursorPosition);
for(size_t x = 0; x < Pos; x++)
WriteConsole(StdOut, " ", 1, &Dummy, 0);
Pos--;
}
aDest[Pos] = 0;
SetConsoleCursorPosition(StdOut, ConsoleScreenBufferInfo.dwCursorPosition);
for(size_t x = 0; x < Pos; x++)
WriteConsole(StdOut, "*", 1, &Dummy, 0);
}
}
int main()
{
StdIn = GetStdHandle(STD_INPUT_HANDLE);
StdOut = GetStdHandle(STD_OUTPUT_HANDLE);
printf("Enter Password:");
fflush(stdout);
char Pass[16];
GetPass(Pass, sizeof(Pass));
printf("\\nYou wrote: %s\\n", Pass);
}
Den kender ikke forskel på store og små bogstaver, kan kun læse a/A -> z/Z