Enumerate multiple keyboards?

Started by
5 comments, last by AntiMight 11 years, 6 months ago
I want get input from two keyboards separately, after a lot of search , I find the function EnumDevice() may help. what I'm trying to do is to enumerate all keyboards, and create as many number of instances of DirectInputDevice with each guid, The problem is that when I pass DI8DEVCLASS_KEYBOARD to EnumDevice(), the callback function cannot enum my usb keyboards. I also tried DI8DEVCLASS_DEVICE, it returns me 3 guid, but none of them match my PS/2 guid.I don't know what devices they are exactly. I have 3 keyboards, one of which is PS/2 and the other via USB, any help? Here is my test program,a console project
struct Keyboard
{
IDirectInputDevice8* device;
GUID guid;
};
#define input Input::Instance()
#define MAXDEVICES 5
class Input
{
private:
IDirectInput8* dinput;
std::vector<Keyboard> keyboards;
private:
Input()
{
DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,
IID_IDirectInput8,(LPVOID*)&dinput, NULL);
}
Input(const Input&);
Input& operator = (const Input&);
public:
static Input* Instance()
{
static Input instance;
return &instance;
}
void EnumKeyboards()
{
if(dinput)
{
dinput->EnumDevices(DI8DEVCLASS_KEYBOARD,
EnumKeyboardsCallBack,
NULL,
DIEDFL_ATTACHEDONLY);
}
}
static BOOL CALLBACK EnumKeyboardsCallBack(LPCDIDEVICEINSTANCE lpddi,
LPVOID pvRef)
{
static int numdevices = 0;
if(numdevices < MAXDEVICES)
{
IDirectInputDevice8* device;
input->dinput->CreateDevice(lpddi->guidInstance, &device, NULL);
Keyboard keyboard = { device, lpddi->guidInstance};
input->keyboards.push_back(keyboard);
numdevices++;
return DIENUM_CONTINUE;
}
return DIENUM_STOP;
}
void printKeyboardsInfo()
{
std::vector<Keyboard>::iterator i = this->keyboards.begin(),
end = this->keyboards.end();
while(i != end)
{
std::cout << i->guid.Data1 <<" "<<i->guid.Data2<<" " << i->guid.Data3<<i->guid.Data4<< std::endl;
++i;
}
}
int KeyboardNumber() { return keyboards.size(); }
};
int main()
{
input->EnumKeyboards();
input->printKeyboardsInfo();
system("pause");
return 0;
}
Advertisement
Now I modified the callback function,and print out the type string of all devices. I got two different guidinstance code from single usb keyboard, but none of them work. I can only get output from my PS/2 keyboard. So Did I make mistakes creating usb keyboard? Sorry for my bad English, I'm not a English speaker. and here is the modified code}
#include <iostream>
#include <dinput.h>
#include <string>
#include <vector>
#pragma comment(lib, "dxguid.lib")
#pragma comment(lib, "dinput8.lib")
#define DIRECTINPUT_VERSION 0x0800
struct Keyboard
{
IDirectInputDevice8* device;
GUID guid;
char key[256];
};
#define input Input::Instance()
#define MAXDEVICES 10
class Input
{
private:
IDirectInput8* dinput;
public:
std::vector<Keyboard> keyboards;
private:
Input()
{
DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,
IID_IDirectInput8,(LPVOID*)&dinput, NULL);
}
Input(const Input&);
Input& operator = (const Input&);
public:
static Input* Instance()
{
static Input instance;
return &instance;
}
bool CreateKeyboards()
{
if(dinput==NULL) return false;
HWND hwnd = GetConsoleWindow();
if(FAILED(dinput->EnumDevices(DI8DEVCLASS_ALL,
EnumKeyboardsCallBack,
NULL,
DIEDFL_ALLDEVICES)))
{
MessageBox(hwnd,"EnumDevices() - FAILED", "Error",0);
return false;
}
int numdevice = keyboards.size();
for(int i = 0; i < numdevice; i++)
{
if(FAILED(keyboards.device->SetDataFormat(&c_dfDIKeyboard)))
{
MessageBox(hwnd, "SetDataFormat() - FAILED","Error",0);
return false;
}
if(FAILED(keyboards.device->SetCooperativeLevel(hwnd,DISCL_FOREGROUND|DISCL_NONEXCLUSIVE)))
{
MessageBox(hwnd, "SetCooperativeLevel() - FAILED", "Error",0);
return false;
}
if(FAILED(keyboards.device->Acquire()))
{
MessageBox(hwnd, "Acquire() - FAILED", "Error",0);
return false;
}
return true;
}
}
static BOOL CALLBACK EnumKeyboardsCallBack(LPCDIDEVICEINSTANCE lpddi,
LPVOID pvRef)
{
std::cout << lpddi->tszInstanceName <<": "<<lpddi->guidInstance.Data1 << std::endl;
std::string typeString = lpddi->tszInstanceName;
static int numdevices = 0;
if(numdevices < MAXDEVICES )
{
if(typeString == "Keyboard"|| typeString=="USB Keyboard"||typeString == "USB Combo Keyboard" )
{
IDirectInputDevice8* device;
input->dinput->CreateDevice(lpddi->guidInstance, &device, NULL);
Keyboard keyboard = { device, lpddi->guidInstance };
input->keyboards.push_back(keyboard);
numdevices++;
}
return DIENUM_CONTINUE;
}
return DIENUM_STOP;
}
void printKeyboardsInfo()
{
int size = keyboards.size();
std::cout <<std::endl <<"Totle "<<size <<" keyboards attached"<<"\n\n";
for(int i = 0; i < size; i++)
{
std::cout <<"Keyboard"<<i<<":"<< keyboards.guid.Data1 << "\n\n";
}
}
int KeyboardNumber() { return keyboards.size(); }
};
int main()
{
if(!input->CreateKeyboards()) return 0;
input->printKeyboardsInfo();
for(int i = 0;i < input->keyboards.size(); i++)
{
std::cout << "keyboard Index:"<<i<<std::endl;
while(!(input->keyboards.key[DIK_N] & 0x80))
{
ZeroMemory(input->keyboards.key,256*sizeof(char));
input->keyboards.device->GetDeviceState(256*sizeof(char),(LPVOID)&input->keyboards.key);
if(input->keyboards.key[DIK_1] & 0x80) {
std::cout << "new input,device guid:"<<input->keyboards.guid.Data1<<std::endl;
Sleep(500);
}
}
}
system("pause");
return 0;
}
here is the output,usb keyboard doesn't response.[attachment=11627:kt.png]
Maybe my memory is at fault but I'm rather sure RAW input will do it way easier.
I've worked my way with WiiMotes, I guess it'll work with keyboards!

I don't know what's about. Why all this effort in keeping DirectInput alive? For keyboard input?

Previously "Krohm"


Maybe my memory is at fault but I'm rather sure RAW input will do it way easier.
I've worked my way with WiiMotes, I guess it'll work with keyboards!

I don't know what's about. Why all this effort in keeping DirectInput alive? For keyboard input?
Hey,Krohm,I really thank you for your reply.I want to make a game that allowing high frequency input with keyboard, I don't know if raw input can handle that. I havn't tried that before, just feel like maybe DirectInput is more efficient for its complexity? Anyway,I will try raw input.

Hey,Krohm,I really thank you for your reply.I want to make a game that allowing high frequency input with keyboard, I don't know if raw input can handle that. I havn't tried that before, just feel like maybe DirectInput is more efficient for its complexity? Anyway,I will try raw input.


As far as I know DirectInput is something that works but it is almost deprecated. Basically DirectInput is just reading the windows messages for input, which you could do also by yourself. Raw input should be slightly more efficient than DirectInput.

Cheers!

I want to make a game that allowing high frequency input with keyboard, I don't know if raw input can handle that.
I don't know what you mean by "high frequency". But I can tell you it has enough throughput to manage hi-dpi mices and wiimotes. I don't think keyboards will cause trouble. I cannot really tell, I never had any trouble with them and I can guarantee you I have bashed my keyboards as fast as humanly possible.

Keep in mind that many keyboards cannot read many buttons at the same time because of an hardware limitation.

If you find that useful, do you mind rating up messages? Hopefully this will also help other people in pinpointing information with ease.

Previously "Krohm"

I'm sorry for replying late.I have solved my problem by using RawInput.And I will paste my unfinished rawinput class here

[quote name='AntiMight' timestamp='1349427821' post='4987056']
Hey,Krohm,I really thank you for your reply.I want to make a game that allowing high frequency input with keyboard, I don't know if raw input can handle that. I havn't tried that before, just feel like maybe DirectInput is more efficient for its complexity? Anyway,I will try raw input.


As far as I know DirectInput is something that works but it is almost deprecated. Basically DirectInput is just reading the windows messages for input, which you could do also by yourself. Raw input should be slightly more efficient than DirectInput.

Cheers!
[/quote]I have read a lot about keyboard input on MSDN, I think you are right, thank you.

[quote name='AntiMight' timestamp='1349427821' post='4987056']
I want to make a game that allowing high frequency input with keyboard, I don't know if raw input can handle that.
I don't know what you mean by "high frequency". But I can tell you it has enough throughput to manage hi-dpi mices and wiimotes. I don't think keyboards will cause trouble. I cannot really tell, I never had any trouble with them and I can guarantee you I have bashed my keyboards as fast as humanly possible.

Keep in mind that many keyboards cannot read many buttons at the same time because of an hardware limitation.

If you find that useful, do you mind rating up messages? Hopefully this will also help other people in pinpointing information with ease.
[/quote]I can handle multiple keyboards inputs now, and thank you for let me knowing the raw input API. Here is the code for handling multiple keyboards with raw input. The principles are basically the same for other devices, like mouse,game controll,etc.[code]
//RawInput.h
#include <Windows.h>
#include <vector>
class RawInput
{
public:
struct KeyboardArgs
{
UINT index; //index in keyboards vector
HANDLE handle; //handle to differentiate devices
UINT vk; //key
};
//enum DeviceType
// {
// DT_KEY,
// DT_MOUSE,
// DT_OEM
// };
//keystroke events, call in ProcessKeyStroke
typedef void (*KeyEventHandler)(KeyboardArgs);
KeyEventHandler KeyDown;
//those 3 event havn't finished
KeyEventHandler KeyPressed;
KeyEventHandler KeyReleased;
KeyEventHandler KeyUp;
private:
HWND hwnd; //the handle for dest window
std::vector<KeyboardArgs> keyboards;
public:
RawInput(HWND h):hwnd(h){}
bool RegisterKeyboard()
{
RAWINPUTDEVICE Rid[1];

Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x06;
Rid[0].dwFlags = 0;
Rid[0].hwndTarget = hwnd;
if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE) {
MessageBox(hwnd, "RegisterRawInputDevices() - FAILED","Error",0);
return false;
}
return true;
}
void RegisterKeyEventHandler( //register for event
KeyEventHandler keyPressFunc,
KeyEventHandler keyDownFunc = 0,
KeyEventHandler keyReleaseFunc = 0,
KeyEventHandler keyUpFunc = 0)
{
KeyPressed = keyPressFunc;
KeyDown = keyDownFunc;
KeyReleased = keyReleaseFunc;
KeyUp = keyUpFunc;
}
//this function will enumerate all the devices
int EnumerateDevices()
{
int NumberOfKeyboards = 0;
UINT deviceCount = 0;
if(GetRawInputDeviceList(NULL, &deviceCount, sizeof(RAWINPUTDEVICELIST)) != 0)
{
MessageBox(hwnd, "GetRawInputDeviceList() - First Call Failed","Error",0);
return -1;
}
RAWINPUTDEVICELIST* rid = new RAWINPUTDEVICELIST[deviceCount];
if(GetRawInputDeviceList(rid, &deviceCount, sizeof(RAWINPUTDEVICELIST)) != deviceCount)
{
MessageBox(hwnd, "GetRawInputDeviceList() - Second Call Failed","Error",0);
return -1;
}
//store all the keyboards handles, and give them indices for identification in game logic
for(int i = 0; i < deviceCount; i++)
{
if (rid.dwType == RIM_TYPEKEYBOARD )
{
KeyboardArgs kb = {NumberOfKeyboards,rid.hDevice};
NumberOfKeyboards++;
keyboards.push_back(kb);
}
}
delete[] rid;
return NumberOfKeyboards;
}
void ProcessKeyStroke(LPARAM lParam)
{
UINT dwSize;
if(GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize,
sizeof(RAWINPUTHEADER)) != 0)
{
MessageBox(hwnd,"GetRawInputData() - First Call Failed","Error",0);
return;
}
LPBYTE lpb = new BYTE[dwSize];
if (lpb == NULL) return;
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,
sizeof(RAWINPUTHEADER)) != dwSize )
{
MessageBox(hwnd,"GetRawInputData() - Second Call Failed","Error",0);
return;
}
RAWINPUT* raw = (RAWINPUT*)lpb;
if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
if(raw->data.keyboard.Message == WM_KEYDOWN || raw->data.keyboard.Message == WM_SYSKEYDOWN)
{
USHORT key = raw->data.keyboard.VKey;
if (key > 0xFE) return;
//a example for call a event
if(KeyDown != NULL)
{
//iterate through all the devices have been enumerated
for(int i = 0; i < keyboards.size();i++)
{//search the keyboard in enumerated keyboards
if(raw->header.hDevice == keyboards.handle)
{
keyboards.vk = key; //change the current key code
KeyDown(keyboards); //call event
}
}
}

}
}
delete[] lpb; //release the rawinput resources
}
};
//---usage
RawInput* input; //global pointer
//init and register callback functions for rawinput somewhere
void init()
{
input = new RawInput(d3d->WindowHandle());
int numkeyboards = input->EnumerateDevices();
input->RegisterKeyEventHandler(KeyPressed,KeyDown);
input->RegisterKeyboard();
}
LRESULT CALLBACK WndProc(
HWND hwnd,
UINT msg,
WPARAM wParam,
LPARAM lParam)
{
switch (msg)
{
case WM_INPUT:
input->ProcessKeyStroke(lParam);
break;
}
}
//an example for KEYDOWN callback
void KeyDown(RawInput::KeyboardArgs args)
{
strstm.str("");
strstm <<"keyboards index:"<< args.index;
}

ok, that's how it looks like. I haven't finish it yet, and still needs to improve it a lot.Anyway, I really hope my post can help someone who also have this problem.

This topic is closed to new replies.

Advertisement