C++控制台程序,windows环境下响应按键消息实现一

转自:http://blog.csdn.net/aizquan/article/details/6869806


[cpp]  view plain copy
  1. BOOL ReadConsoleInput(  
  2.   HANDLE hConsoleInput, //输入句柄  
  3.   PINPUT_RECORD lpBuffer, //指向INPUT_RECORD结构体(数组)的指针  
  4.   DWORD nLength, //上面那个结构体的大小  
  5.   LPDWORD lpNumberOfEventsRead //实际读入输入内容的个数  
  6. );  
[cpp]  view plain copy
  1. #pragma once  
  2. #include <Windows.h>class GohanConsoleHelper  
  3. {  
  4.     HANDLE _hIn;  
  5.     HANDLE _hOut;  
  6.     INPUT_RECORD _InRec;  
  7.     DWORD _NumRead;  
  8. public:  
  9.     WORD VKey;  
  10.     GohanConsoleHelper(void){  
  11.         _hIn = GetStdHandle(STD_INPUT_HANDLE);  
  12.         _hOut = GetStdHandle(STD_OUTPUT_HANDLE);  
  13.         VKey=0;  
  14.     }  
  15.     bool ReadOneInput()  
  16.     {  
  17.         return 0!=ReadConsoleInput(_hIn,&_InRec,1,&_NumRead);  
  18.     }  
  19.     bool ReadOneInput(INPUT_RECORD& InRec)  
  20.     {  
  21.         return 0!=ReadConsoleInput(_hIn,&InRec,1,&_NumRead);  
  22.     }  
  23.     DWORD ReadKeyDown()  
  24.     {  
  25.         if(!ReadConsoleInput(_hIn,&_InRec,1,&_NumRead))  
  26.             return 0;  
  27.         if(_InRec.EventType!=KEY_EVENT)  
  28.             return 0;  
  29.         if(_InRec.Event.KeyEvent.bKeyDown > 0)  
  30.             return 0;  
  31.         VKey = _InRec.Event.KeyEvent.wVirtualKeyCode;  
  32.         return VKey;  
  33.     }  
  34.     DWORD ReadKeyPush()  
  35.     {  
  36.         if(!ReadConsoleInput(_hIn,&_InRec,1,&_NumRead))  
  37.             return 0;  
  38.         if(_InRec.EventType!=KEY_EVENT)  
  39.             return 0;  
  40.         if(_InRec.Event.KeyEvent.bKeyDown == 0)  
  41.             return 0;  
  42.         VKey = _InRec.Event.KeyEvent.wVirtualKeyCode;  
  43.         return VKey;  
  44.     }  
  45. public:  
  46.     ~GohanConsoleHelper(void){}  
  47. };  
[cpp]  view plain copy
  1. #include <windows.h>  
  2. #include <iostream>  
  3. #include "GohanConsoleHelper.h"  
  4. using namespace std;int main()  
  5. {  
  6.     GohanConsoleHelper gch;  
  7.     while (true)  
  8.     {  
  9.         if(gch.ReadKeyPush()!=0) //使用ReadKeyDown()捕获按键弹起的VK_CODE  
  10.         {  
  11.             if(gch.VKey != VK_ESCAPE)  
  12.                 cout<<"VK_CODE == "<<gch.VKey<<endl;  
  13.             else {  
  14.                 cout<<"Bye~~"<<endl;  
  15.                 break;  
  16.             }  
  17.         }  
  18.     }  
  19.     return 0;  
  20. }  

另外,钩子实现请看:http://blog.csdn.net/gamewyd/article/details/6868290

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值