zomgistania

Main page | About | Articles | Previous Posts | Archives

Sunday, May 07, 2006

Keyboard hooks revisited

I realized there's an even simpler way to make a global keyboard hook than the way I demonstrated earlier, though this method requires DirectX.

Using the DirectInput Device class for acquiring the keyboard you can create a global keyboard hook. It's very simple, just a matter of few lines of code

The following code could be used for hooking the keyboard


using DXI = Microsoft.DirectX.DirectInput;

//this is taken from my keyboard handler class
//keyboard is a DXI.Device in the class.
public void AcquireKeyboard(System.Windows.Forms.Control parent)
{
keyboard = new DXI.Device(DXI.SystemGuid.Keyboard);
keyboard.SetDataFormat(DXI.DeviceDataFormat.Keyboard);

keyboard.SetCooperativeLevel(parent,
DXI.CooperativeLevelFlags.Background |
DXI.CooperativeLevelFlags.NonExclusive);


keyboard.Properties.BufferSize = 10;

keyboard.Acquire();
}

Reading the keyboard input could be done with the following


DXI.BufferedDataCollection dataCollection = keyboard.GetBufferedData();
DXI.Key key;

if (dataCollection != null)
{
//loop through the keys changed
foreach (DXI.BufferedData data in dataCollection)
{
key = (DXI.Key)data.Offset;
//now we have the key
//do something with it here
}
}


In the above code, data.ButtonPressedData is 1 if the key was pressed down and 0 if the key was lifted.

With this method though, you won't get an event notification when a key state is changed. You have to make a loop which checks the key state and write your own event or such.

Here's my keyboardmanager class code
I don't know if it's any good, but it works well enough at least for now... and it has events which get triggered properly.
To acquire the KB, just call the AcquireKeyboard method with the form as a parameter and make a loop which calls Update()

1 Comments:

Post a Comment

<< Home