给你个api函数写的程序,可以捕捉你的键盘,你就可以捕捉键盘的输入消息。
#include <windows.h>
#include <stdio.h>
VOID ErrorExit(LPSTR);
VOID KeyEventProc(KEY_EVENT_RECORD);
int main(VOID)
{
HANDLE hStdin;
DWORD cNumRead, fdwMode, fdwSaveOldMode, i;
INPUT_RECORD irInBuf[128];
int counter=0;
//获得标准输入句柄
hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (hStdin == INVALID_HANDLE_VALUE)
ErrorExit("GetStdHandle");
//保存旧模式
if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )
ErrorExit("GetConsoleMode");
//新输入模式
fdwMode = ENABLE_WINDOW_INPUT;
//设置新模式
if (! SetConsoleMode(hStdin, fdwMode) )
ErrorExit("SetConsoleMode");
while (counter++ <= 100) {
//获取输入
if (! ReadConsoleInput(
hStdin,
// input buffer handle
irInBuf,
// buffer to read into
128,
// size of read buffer
&cNumRead) ) // number of records read
ErrorExit("ReadConsoleInput");
//根据输入大小,不要64k
for (i = 0; i < cNumRead; i++) {
if(irInBuf[i].EventType==KEY_EVENT) KeyEventProc(irInBuf[i].Event.KeyEvent);
}
}
return 0;
}
VOID ErrorExit (LPSTR lpszMessage)
{
fprintf(stderr, "%s\n", lpszMessage);
ExitProcess(0);
}
VOID KeyEventProc(KEY_EVENT_RECORD ker)
{
printf("Key event: ");
if(ker.bKeyDown)
printf("key pressed:%c\n",ker.uChar.AsciiChar);
else printf("key released\n");
}