DirectInput之查詢鍵盤

DirectInput之查詢鍵盤

DirectInput是DirectX COM組件之一. 它讓你無需理會『鍵盤』硬件驅動程式. DirectInput為輸入設備提供統一接口,當然輸入設備需已安裝硬件驅動.而且你需要安裝『DirectX SDK』並設定include和LIB搜索路徑,或者加入工程項目中.若你想讀取鍵盤狀態.用法與GetAsyncKeyState()使用基本相似.但它的KEY鍵並非是ASCII碼.若你有多個鍵盤.則所有的輸入合併到單一設備中.

演示程式按鍵盤在屏幕中顯示對應字母:下載

演示代碼.在Init()中調用當然你需檢測返回值HRESULT

1.調用DirectInputCreate()生成IDirectInput接口

IDirectInput * direct_input;

DirectInputCreate(GetModuleHandle(NULL),DIRECTINPUT_VERSION, &direct_input,NULL);

2.獲取鍵盤, GUID_SysKeyboard為全域主鍵盤設備ID碼

IDirectInputDevice * direct_keyboard;

direct_input->CreateDevice(GUID_SysKeyboard, &direct_keyboard, NULL);

3.設置鍵盤協作等級, 非獨占訪問,訪問該設備時不會干涉其它應用程序訪問該設備. 並且當應用程序在前臺和後臺時都能時用該設備.

direct_keyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE |DISCL_BACKGROUND);

4.設置數據格式. c_dfDIKeyboard為DirectInput通用鍵盤全域常量

direct_keyboard->SetDataFormat(&c_dfDIKeyboard);

5.從DirectInput獲取鍵盤.

direct_keyboard->Acquire();

6.你現在以可以從鍵盤中獲取輸入.在你Update()更新中獲取鍵盤狀態.若你失去設備鍵盤,需要重新從DirectInput獲取鍵盤

while(direct_keyboard->GetDeviceState(sizeof(UCHAR) * 256, direct_keystate)== DIERR_INPUTLOST)

{

if(direct_keyboard->Acquire() != S_OK)

return false;

}

7.當你退出遊戲時.需要釋放鍵盤和DirectInput對像

direct_keyboard->Release();

direct_input->Release();

評論