DirectInput输入——键盘设备
工程添加以下库:dxguid.lib
d3d9.lib
d3dx9.lib
winmm.lib
dinput8.lib
包含头文件:#include "dinput.h"
/* **全局变量: */ //主DInput COM对象 LPDIRECTINPUT8 lpdi = NULL; //键盘设备(所有设备的类型都是IDIRECTINPUTDEVICE8) LPDIRECTINPUTDEVICE8 lpdikey = NULL; //包含键盘状态表,获取的键盘状态放在此结构中 UCHAR keyboard_state[256]; /* **主DInput COM对象的创建与释放: */ //创建主DirectInput对象 if(FAILED(::DirectInput8Create(main_instance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&lpdi, NULL))) { return 0; } //释放主COM对象 if(lpdi) lpdi->Release(); /* **键盘设备的初始化、读取、释放 */ int DInput_Init_Keyboard(void); int DInput_Read_Keyboard(void); void DInput_Release_Keyboard(void); //初始化键盘设备 int DInput_Init_Keyboard(void) { //创建键盘设备 if(FAILED(lpdi->CreateDevice(GUID_SysKeyboard, &lpdikey, NULL))) { return 0; } //设置键盘协作等级,设置为后台/非独占模式 if(FAILED(lpdikey->SetCooperativeLevel(main_window_handle, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) { return 0; } //设置键盘的数据格式,键盘对应的数据格式为c_dfDIKeyboard if(FAILED(lpdikey->SetDataFormat(&c_dfDIKeyboard))) { return 0; } //获取键盘 if(FAILED(lpdikey->Acquire())) { return 0; } return TRUE; } //读取键盘数据 int DInput_Read_Keyboard(void) { if (lpdikey) { if (lpdikey->GetDeviceState(256, (LPVOID)keyboard_state)!=DI_OK) return(0); } else { memset(keyboard_state,0,sizeof(keyboard_state)); return(0); } return(1); } //释放键盘 void DInput_Release_Keyboard(void) { if (lpdikey) { //获取后,归还 lpdikey->Unacquire(); //释放 lpdikey->Release(); } } //读取键盘数据并使用 #define DIKEYDOWN(data,n) (data[n] & 0x80) //主循环中: DInput_Read_Keyboard(); if((keyboard_state[DIK_F1] & 0x80) || (keyboard_state[DIK_A] & 0x80)) { //... } if(DIKEYDOWN(keyboard_state, DIK_ESCAPE)) { //... } if(keyboard_state[DIK_F1]) { //... } //读取键盘数据版本二,检查设备是否丢失 int DInput_Read_Keyboard(void) { HRESULT result; //在Game循环中,读取设备数据时,轮询查询是被是否丢失 while(result = lpdikey->GetDeviceState(256, (LPVOID)keyboard_state) == DIERR_INPUTLOST) { if(FAILED(result = lpdikey->Acquire())) //重新获取设备 { break; } } if(FAILED(result)) { return 0; } }