此代码打印输入按钮后输入的用户类型。
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()的虚拟密钥代码,但无法完成它。
关于如何实现这样的事情的任何想法。
提前致谢。
答案 0 :(得分:1)
注意虚拟键码。像这样:
if (eventBuffer.EventType == KEY_EVENT) {
if(eventBuffer.Event.KeyEvent.bKeyDown) {
switch (eventBuffer.Event.KeyEvent.wVirtualKeyCode) {
case VK_DOWN: printf("Down arrow pressed\n"); break;
case VK_UP: printf("Up arrow pressed\n"); break;
default: {
// Rest of your code...
}