控制台程序怎么得知光标(方向)键按下了
用扫描码?
具体的怎么做?
[解决办法]
getchar()
[解决办法]
用ReadConsoleInput,具体说明去MSDN上看下,给个例子:
while(1){ INPUT_RECORD irInBuf; DWORD cNumRead; ReadConsoleInput(GetStdHandle(STD_INPUT_HANDLE),&irInBuf,1,&cNumRead); if(irInBuf.EventType == KEY_EVENT && irInBuf.Event.KeyEvent.bKeyDown == TRUE) { if(irInBuf.Event.KeyEvent.wVirtualKeyCode == 38 && GetConsoleWindow()==GetForegroundWindow()) { //按了上 } else if(irInBuf.Event.KeyEvent.wVirtualKeyCode == 40 && GetConsoleWindow()==GetForegroundWindow()) { //按了下 } else if(irInBuf.Event.KeyEvent.wVirtualKeyCode == 37 && GetConsoleWindow()==GetForegroundWindow()) { //按了左 } else if(irInBuf.Event.KeyEvent.wVirtualKeyCode == 39 && GetConsoleWindow()==GetForegroundWindow()) { //按了右 } }}
[解决办法]
方法二:
#define KEY_UP 0xE048#define KEY_DOWN 0xE050#define KEY_LEFT 0xE04B#define KEY_RIGHT 0xE04Dint GetKey(){ int nkey=getch(),nk=0; if(nkey>=128||nkey==0)nk=getch(); return nk>0?nkey*256+nk:nkey;}
[解决办法]
//The _getch function reads a single character from the console without echoing.//Function can not be used to read CTRL+Break.//When reading a function key or an arrow key,//_getch must be called twice; the first call returns 0 or 0xE0,//and the second call returns the actual key code.#include <conio.h>#include <windows.h>void main() { unsigned short k; while (1) { Sleep(100); k=getch(); if (27==k) break;//按Esc键退出 if (0==k||0xe0==k) k|=getch()<<8;//非字符键 cprintf("%04x pressed.\r\n",k); }}