Original Post
For my game I needed a function similar to cin (the C++ standart input handler). It should work the same accept for the fact, that it should return a pointer to a string and that ist should print the input echo in color.
So I wrote this function:
It basically works. But sometimes characters are printed doubled or not at all (especially when I press the shift key).
If you have any tips on solving this problem or other optimizations, pleeeeeeaaze reply. This function will be used a lot in my game and I want it to work properly. And I guess we can figure it out much faster when we all think about the problem than if I had to do this on my own.
"Mr Sandman bring me a dream"
char *GetInput()
{
char *Buffer;
static char buf[100];
COORD OldCursorPos;
COORD StartPos;
DWORD BufLength = 0;
Buffer = buf;
GetConsoleScreenBufferInfo(hOutput, &ScreenBuffer);
OldCursorPos.X = ScreenBuffer.dwCursorPosition.X;
OldCursorPos.Y = ScreenBuffer.dwCursorPosition.Y;
StartPos.X = ScreenBuffer.dwCursorPosition.X;
StartPos.Y = ScreenBuffer.dwCursorPosition.Y;
ReadConsoleInput(hInput, &record, 1, &cRead);
record.EventType = NULL;
while (1)
{
while (record.EventType != KEY_EVENT)
ReadConsoleInput(hInput, &record, 1, &cRead);
GetConsoleScreenBufferInfo(hOutput, &ScreenBuffer);
ReadConsoleInput(hInput, &record, 1, &cRead);
if(isalnum(record.Event.KeyEvent.uChar.AsciiChar))
{
WriteString(CursorPos.X, CursorPos.Y, &record.Event.KeyEvent.uChar.AsciiChar);
CursorPos.X = ScreenBuffer.dwCursorPosition.X + 1;
CursorPos.Y = ScreenBuffer.dwCursorPosition.Y;
SetConsoleCursorPosition(hOutput, CursorPos);
BufLength++;
}
if (record.Event.KeyEvent.wVirtualKeyCode == VK_BACK)
{
if (CursorPos.X != OldCursorPos.X)
{
CursorPos.X = ScreenBuffer.dwCursorPosition.X - 1;
CursorPos.Y = ScreenBuffer.dwCursorPosition.Y;
SetConsoleCursorPosition(hOutput, CursorPos);
BufLength--;
}
WriteString(CursorPos.X, CursorPos.Y, " ");
}
else if (record.Event.KeyEvent.wVirtualKeyCode == VK_SPACE)
{
WriteString(CursorPos.X, CursorPos.Y, " ");
CursorPos.X = ScreenBuffer.dwCursorPosition.X + 1;
CursorPos.Y = ScreenBuffer.dwCursorPosition.Y;
SetConsoleCursorPosition(hOutput, CursorPos);
if ((CursorPos.X - 1) == StartPos.X)
StartPos.X++;
else
BufLength++;
}
else if (record.Event.KeyEvent.wVirtualKeyCode == VK_RETURN)
{
ReadConsoleOutputCharacter(hOutput, Buffer, BufLength, StartPos, &cRead);
break;
}
record.EventType = NULL;
}
return(Buffer);
}
|