• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
AntiMight

Enumerate multiple keyboards?

6 posts in this topic

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 [CODE]
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;
}
[/CODE] Edited by AntiMight
0

Share this post


Link to post
Share on other sites
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}
[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[i].device->SetDataFormat(&c_dfDIKeyboard)))
{
MessageBox(hwnd, "SetDataFormat() - FAILED","Error",0);
return false;
}
if(FAILED(keyboards[i].device->SetCooperativeLevel(hwnd,DISCL_FOREGROUND|DISCL_NONEXCLUSIVE)))
{
MessageBox(hwnd, "SetCooperativeLevel() - FAILED", "Error",0);
return false;
}
if(FAILED(keyboards[i].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[i].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[i].key[DIK_N] & 0x80))
{
ZeroMemory(input->keyboards[i].key,256*sizeof(char));
input->keyboards[i].device->GetDeviceState(256*sizeof(char),(LPVOID)&input->keyboards[i].key);
if(input->keyboards[i].key[DIK_1] & 0x80) {
std::cout << "new input,device guid:"<<input->keyboards[i].guid.Data1<<std::endl;
Sleep(500);
}
}
}
system("pause");
return 0;
}
[/CODE]here is the output,usb keyboard doesn't response.[attachment=11627:kt.png] Edited by AntiMight
0

Share this post


Link to post
Share on other sites
Maybe my memory is at fault but I'm rather sure [url="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645571(v=vs.85).aspx"]RAW input[/url] will do it way [url="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645590(v=vs.85).aspx"]easier[/url].
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?
1

Share this post


Link to post
Share on other sites
[quote name='Krohm' timestamp='1349423929' post='4987049']
Maybe my memory is at fault but I'm rather sure [url="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645571(v=vs.85).aspx"]RAW input[/url] will do it way [url="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645590(v=vs.85).aspx"]easier[/url].
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?
[/quote]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.
0

Share this post


Link to post
Share on other sites
[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.
[/quote]

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!
1

Share this post


Link to post
Share on other sites
[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.[/quote]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. Edited by Krohm
0

Share this post


Link to post
Share on other sites
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='kauna' timestamp='1349439294' post='4987086']
[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.
[/quote]

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='Krohm' timestamp='1349440499' post='4987092']
[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.[/quote]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][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[i].dwType == RIM_TYPEKEYBOARD )
{
KeyboardArgs kb = {NumberOfKeyboards,rid[i].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[i].handle)
{
keyboards[i].vk = key; //change the current key code
KeyDown(keyboards[i]); //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;
}
[/CODE]
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. Edited by AntiMight
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0