InterestGroupDirectx/VbNetTutorials/DirectInput9/ImmediateFeedbackKeyboard

Written by JustinDaubenmire

This tutorial shows you the basic startup tasks to use the keyboard using DirectInput version 9 and vb.net. It assumes the following:

If you do not have the DirectX 9 SDK installed on your computer, prior to trying this source code, please download [WWW] The DirectX 9 SDK and install it.

Ok, lets get started. Open up Visual Studio 2003 and start a new vb.net windows application project and name it KeyboardTest.

Once the project appears, you'll see that it has Form1 in the solution explorer. We'll be using this form to put all of our code in.

Now you have to set a reference to microsoft.DirectX and Microsoft.DirectX.DirectInput prior to programming anything. You do this by going to the project menu, alt+p, then go to add reference... and press enter or press the letter r.

When the new screen appears, in the list of components, down arrow until you get to Microsoft.DirectX. Once on it, press alt+e to activate the select button. It will be added to the list of "selected references". Continue to down arrow until you arive at Microsoft.DirectX.DirectInput. Once on it, press alt+e to activate the select button. Now you have added both references to the "selected components" list. Finally, just tab to the ok button and press enter. Now you have set a reference to Microsoft.DirectX and Microsoft.DirectX.DirectInput. You can now begin to program the keyboard test application.

Your project has form1 already added to it. Open up the code editor for form1 and add these import statements to the top of form1 above the line Public Class Form1:

Imports Microsoft.DirectX
Imports Microsoft.DirectX.DirectInput

Now in the form1 class, just under the text "#Region Windows Form Designer generated code" add these variables...

' used for keyboard

    Private oDev As Device = Nothing

    ' used for loop to test for keystrokes
    ' in the function TestForKeyPress

    Private blnRunning As Boolean = False

    ' used to test if we have control of the keyboard
    ' or if another application has stolen it from us
    ' in the function IsKeyboardAquired 

    Private blnKeyboardAquired As Boolean = False

    ' used to tell what key we have pressed in the function TestForKeyPress 

    Private oKeyboardState As KeyboardState = Nothing

   

Now in the form load event, we are going to setup the keyboard. Here is the code with comments:

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Try

        ' show the form so we can get a handle to it
        Me.Show()

        ' setup a new device and tell the system it is a keyboard
        oDev = New DirectInput.Device(DirectInput.SystemGuid.Keyboard)

        ' set CooperativeLevel of keyboard
        ' using the form we just showed
            oDev.SetCooperativeLevel(Me, CooperativeLevelFlags.Background Or CooperativeLevelFlags.NonExclusive)


        ' take control of the keyboard now

        oDev.Acquire()

            ' set this flag so our code knows we have the keyboard
            blnKeyboardAquired = True

        ' set this flag for the keyboard loop
            ' in the function TestForKeyPress
            blnRunning = True

        ' start the loop now that asks for keystrokes
            Me.TestForKeyPress()

        Catch ex As Exception
            MessageBox.Show(ex.Message)
            ' get rid of device do not need it
            ' was an error trying to acquire it
            oDev.Dispose()

            Application.Exit()

        End Try


    End Sub

A couple of things you'll notice here in the form load. We set the keyboards cooperative level to background or nonexclusive. There are other flags you can use to setup the keyboard such as forground and exclusive. All these flags do is tell DirectInput how the keyboard should react to other applications trying to get access to the keyboard or when your application loses focus.

If we try to gain access to the keyboard and get an error, we jump to the catch ex as exception branch and shut down and exit the application.

If we do gain access, we set a boolean variable blnKeyboardAquired to true letting our code know we have access to the keyboard. That is important to know in your source code since you could lose access to the keyboard and if you do, and then try to process keystrokes, you'll get an error. So, in your code, you have to always test to make certain you still have control of the keyboard. I have a function to do this I'll show you in a bit but first, the line

Me.TestForKeyPress() 

in the form load calls a public function in our class that enters an infinite loop and tests for specific keystrokes. I know, infinite loops are normally bad but all games use them as the main loop for any game believe it or not. So, prior to calling our function TestForKeyPress to actually test for keys being pressed, we set a boolean variable blnRunning to true. While that is true, we will always be looping and monitoring for exact key presses in our public function TestForKeyPress. Here is that function. Copy it and paste it below the words End Sub for the form1 load event. I.E the function is directly below the form1 load sub.

' ***
    ' Function name: TestForKeyPress
    ' Description: tests for various keys that are pressed on the keyboard
    ' Parameters: none
    ' returns: none
    ' ***

    Public Function TestForKeyPress()


        Do While blnRunning = True

            ' make certain application does not lock up
            ' in this loop
            Application.DoEvents()

            ' make certain we still have control of the keyboard
            ' and it was not stolen from another application
            If Me.IsKeyboardAquired = True Then
                ' lets test for various keystrokes now

                ' is the current key left control?
                If oDev.GetCurrentKeyboardState(Key.LeftControl) Then
                    MessageBox.Show("left control was pressed")
                End If

                ' is the a key pressed

                If oDev.GetCurrentKeyboardState(Key.A) Then
                    MessageBox.Show("the key a was pressed")
                End If

                ' is the current key escape?
                If oDev.GetCurrentKeyboardState(Key.Escape) Then
                    MessageBox.Show("escape pressed now ending program")

                    ' set this to exit the loop now
                    blnRunning = False


                End If
            End If

Loop
        ' out of loop end program

        Application.Exit()




    End Function

Notice the line Do While blnRunning = True. That gets us into our infinite loop and we test for various keystrokes in the code. If we hit one we are looking for, we show a message box on the screen. If we hit escape, we set that boolean to false to exit the loop and then end the application. Note, some screen readers you have to let keys pass through for this to work. I.E for JFW, you have to hit insert+3 to pass a key through and then hit escape to get it to work. Screen readers interfere with DirectInput while using the keyboard.

Finally, we need a function to call in the infinite loop to always check if we still have control of the keyboard. That line of code is like this in the loop:

If Me.IsKeyboardAquired = True Then

and that line calls our function name IsKeyboardAquired to see if we still have control of the keyboard. that function looks like this, copy it to the clipboard and then paste it directly after our function TestForKeyPress.

' ***
    ' Function name: IsKeyboardAquired
    ' Description: tests to see if our application still has control of the keyboard
    ' Parameters: none
    ' Returns: true if our application has control of the keyboard
    ' false if it does not have control of it any more
    ' ***

    Public Function IsKeyboardAquired() As Boolean
        'Return true if keyboard is still aquired, return false if it is not
        Try
            If Not blnKeyboardAquired Then
                ' lost keyboard to another application
                ' try to get it back

                oDev.Acquire()
                blnKeyboardAquired = True
            End If

            Return True
        Catch ex As Exception
            ' we were not able to get the keyboard

            blnKeyboardAquired = False
            Return False
        End Try
    End Function

So you see that blnKeyboardAquired is set to true if we can gain access to it in this function and then set to false if we cannot. Then in the infinite loop in the function TestForKeyPress, we test this blnKeyboardAquired variable prior to trying to test for keystrokes. If it is true, this means we have access to the keyboard and can test for keystrokes. If it is false, we skip processing keys until we gain access to the keyboard once again.

last edited 2005-03-22 17:57:56 by JustinDaubenmire