• 文章
  • getch() 的替代方案
釋出
2010年2月22日 (最後更新: 2010年2月24日)

getch() 的替代方案

評分: 3.4/5 (95 票)
*****
好吧,我看到很多人建議使用非標準的 getch() 或 _getch()。

請不要使用 conio.h 庫,因為它不可靠且非標準。MSV C++ 08 中的 conio.h 與 Mingw C 中的有很大不同。
其中許多函式,如 textcolor()、cprintf 等,已被棄用,並且有其他替代方案。

在這裡,我將釋出一個使用 Win API 的 getch() 替代方案。
哦,它只能在 Windows 上執行……
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <windows.h>
CHAR GetCh (VOID)
{
  HANDLE hStdin = GetStdHandle (STD_INPUT_HANDLE);
  INPUT_RECORD irInputRecord;
  DWORD dwEventsRead;
  CHAR cChar;

  while(ReadConsoleInputA (hStdin, &irInputRecord, 1, &dwEventsRead)) /* Read key press */
    if (irInputRecord.EventType == KEY_EVENT
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_SHIFT
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_MENU
	&&irInputRecord.Event.KeyEvent.wVirtualKeyCode != VK_CONTROL)
    {
      cChar = irInputRecord.Event.KeyEvent.uChar.AsciiChar;
	ReadConsoleInputA (hStdin, &irInputRecord , 1, &dwEventsRead); /* Read key release */
	return cChar;
    }
  return EOF;
}

上面的程式碼應該有效,因為它對我有效。

歡迎提出建議和改進。我是這個領域的菜鳥。