此代码在按下输入按钮后打印出用户键入的内容。
main()
{
HANDLE stdinInput = 0;
DWORD numEvents = 0;
DWORD numEventsRead = 0;
DWORD numReceivedRecords = 0;
DWORD fdwSaveOldMode;
DWORD fdwMode;
char dataBuffer[100];
int bufferLen = 0;
stdinInput = GetStdHandle(STD_INPUT_HANDLE);
if (stdinInput == INVALID_HANDLE_VALUE)
perror("GetStdHandle");
if (! GetConsoleMode(stdinInput, &fdwSaveOldMode) )
perror("GetConsoleMode");
fdwMode = ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT;
if (! SetConsoleMode(stdinInput, fdwMode) )
perror("SetConsoleMode");
for(; ; )
{
GetNumberOfConsoleInputEvents(stdinInput, &numEvents);
if (numEvents != 0) {
INPUT_RECORD eventBuffer;
ReadConsoleInputA(stdinInput, &eventBuffer, 1, &numEventsRead);
if (eventBuffer.EventType == KEY_EVENT) {
if(eventBuffer.Event.KeyEvent.bKeyDown)
{
if(eventBuffer.Event.KeyEvent.uChar.UnicodeChar != 0)
{
printf("%c",eventBuffer.Event.KeyEvent.uChar.UnicodeChar);
dataBuffer[bufferLen++] = eventBuffer.Event.KeyEvent.uChar.UnicodeChar;
dataBuffer[bufferLen] = '\0';
if ( dataBuffer[bufferLen] == 99 || eventBuffer.Event.KeyEvent.uChar.UnicodeChar == '\r' ) {
printf("User Wrote: %s\n",dataBuffer);
memset(dataBuffer,0,sizeof(dataBuffer));
bufferLen = 0;
}
}
}
}
}
}
}
现在我想让它检测用户何时按下向上/向下箭头并打印出“按下向上/向下箭头”而无需按 Enter。
考虑使用带有 GetKeyState() 的虚拟键码,但无法完成。
关于如何实现这样的事情的任何想法。
提前致谢。