SlimDX DirectInput Initialization

Nick Udell picture Nick Udell · Feb 8, 2011 · Viewed 7.7k times · Source

I've recently swapped from MDX 2.0 to SlimDX, using Direct3D 11, but I'm struggling to implement keyboard and mouse controls.

In MDX you can use

keyb = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
keyb.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
keyb.Acquire();

to set up a keyboard interface, however SlimDX has a different method. In SlimDX the Device is an abstract class, instead there is a Keyboard class that must be initialized by passing in a DirectInput object, but I can't for the life of me work out how to create a DirectInput object or what it's for.

As far as I can find documentation is pretty slim for SlimDX, if anybody knows of any good resources for learning its particular quirks that would be fantastic, thanks.

Answer

hitzi picture hitzi · Feb 8, 2011

I used it in this way. The mouse handling is the same.

using SlimDX.DirectInput;

private DirectInput directInput;
private Keyboard keyboard;

[...]

//init
directInput = new DirectInput();
keyboard = new Keyboard(directInput);
keyboard.SetCooperativeLevel(form, CooperativeLevel.Nonexclusive | CooperativeLevel.Background);
keyboard.Acquire();

[...]

//read
KeyboardState keys = keyboard.GetCurrentState();

But you should use SlimDX.RawInput because Microsoft recommends it:

While DirectInput forms a part of the DirectX library, it has not been significantly revised since DirectX 8 (2001-2002). Microsoft recommends that new applications make use of the Windows message loop for keyboard and mouse input instead of DirectInput (as indicated in the Meltdown 2005 slideshow[1]), and to use XInput instead of DirectInput for Xbox 360 controllers.

(http://en.wikipedia.org/wiki/DirectInput)

A rawinput mouse sample (keyboard is nearly the same):

SlimDX.RawInput.Device.RegisterDevice(UsagePage.Generic, UsageId.Mouse, SlimDX.RawInput.DeviceFlags.None);
            SlimDX.RawInput.Device.MouseInput += new System.EventHandler<MouseInputEventArgs>(Device_MouseInput);

Now you can react on the events.