Win32命令行應用,ReadConsoleInput()得到鍵盤VK_CODE
ReadConsoleInput是一個Win32 API, 聲明如下:
BOOL ReadConsoleInput(
HANDLE hConsoleInput, //輸入句柄
PINPUT_RECORD lpBuffer, //指向INPUT_RECORD結構體(數組)的指針
DWORD nLength, //上面那個結構體的大小
LPDWORD lpNumberOfEventsRead //實際讀入輸入內容的個數
);
我把讀入的功能寫在這個助手類中,ReadConsoleInput的得到VK_CODE的方法可以看ReadKeyDown和ReadKeyPush兩個函數,它們的效果略有點不同。右圖是效果截圖,按ESC跳出循環。助手類以后還可以添加顏色控制位置控制等功能,只要你想,目的就是為了簡化API調用。
#pragma once
#include <Windows.h>
class GohanConsoleHelper
{
HANDLE _hIn;
HANDLE _hOut;
INPUT_RECORD _InRec;
DWORD _NumRead;
public:
WORD VKey;
GohanConsoleHelper(void){
_hIn = GetStdHandle(STD_INPUT_HANDLE);
_hOut = GetStdHandle(STD_OUTPUT_HANDLE);
VKey=0;
}
bool ReadOneInput()
{
return 0!=ReadConsoleInput(_hIn,&_InRec,1,&_NumRead);
}
bool ReadOneInput(INPUT_RECORD& InRec)
{
return 0!=ReadConsoleInput(_hIn,&InRec,1,&_NumRead);
}
DWORD ReadKeyDown()
{
if(!ReadConsoleInput(_hIn,&_InRec,1,&_NumRead))
return 0;
if(_InRec.EventType!=KEY_EVENT)
return 0;
if(_InRec.Event.KeyEvent.bKeyDown > 0)
return 0;
VKey = _InRec.Event.KeyEvent.wVirtualKeyCode;
return VKey;
}
DWORD ReadKeyPush()
{
if(!ReadConsoleInput(_hIn,&_InRec,1,&_NumRead))
return 0;
if(_InRec.EventType!=KEY_EVENT)
return 0;
if(_InRec.Event.KeyEvent.bKeyDown == 0)
return 0;
VKey = _InRec.Event.KeyEvent.wVirtualKeyCode;
return VKey;
}
public:
~GohanConsoleHelper(void){}
};
main所在文件內容
#include <windows.h>
#include <iostream>
#include "GohanConsoleHelper.h"
using namespace std;
int main()
{
GohanConsoleHelper gch;
while (true)
{
if(gch.ReadKeyPush()!=0) //使用ReadKeyDown()捕獲按鍵彈起的VK_CODE
{
if(gch.VKey != VK_ESCAPE)
cout<<"VK_CODE == "<<gch.VKey<<endl;
else {
cout<<"Bye~~"<<endl;
break;
}
}
}
return 0;
}
在命令行得到VK_CODE可以干許多事情了,可以寫個在Win32命令行下的小游戲,俄羅斯方塊啊什么的,呵呵,不過畫面稍微好點的就搞不了了,因為畢竟win32命令行分辨率太低了。
忘了放出參考的資料:
http://adrianxw.dk/ 比較全面的Win32命令行教程
posted on 2008-05-23 00:08 Gohan 閱讀(6165) 評論(5) 編輯 收藏 引用 所屬分類: C++ 、Practise