1

Edit: It seems I found the reason myself. I had just forgot to acquire the keyboard device before starting the thread. Luckily this was an easy problem. After adding kbd.Acquire(); before the thread call, the code started to work.

Will of course then need the corresponding kbd.Unacquire(); in the handler of the Close button.

Original question

I'm new to DirectInput and threading. Could someone please guide me what's wrong in the code below. It seems I never get any notifications that would trigger my event handler thread.

[Using block omitted. Currently uses SlimDX for DirectInput]

Main form class contains definitions for the variables needed.

public partial class MainForm : Form
{
    private static bool appClosing = false;
    private DirectInput directInput;
    private Keyboard kbd;
    private static AutoResetEvent kbdEvent = new AutoResetEvent(false);
    Thread kbdThread = new Thread(new ThreadStart(Device_KeyboardInput));

    //Application uses windows forms with default settings.

    public MainForm()
    {
        InitializeComponent();
    }

    //When form is loaded, the intention is to properly init the variables and start the thread that should activated by DirectInput.

    private void MainForm_Load(object sender, EventArgs e)
    {
        directInput = new DirectInput();
        kbd = new Keyboard(directInput);
        kbd.SetNotification(kbdEvent);
        kbdThread.Start();
    }

    //Just as a first try, the application should show a simple message when it receives the signal. For a reason currently unknown to me, this never seems to happen.

    static void Device_KeyboardInput() //object sender, EventArgs e)
    {
        while (!appClosing)
        {
            kbdEvent.WaitOne();
            if (!appClosing)
            {
                MessageBox.Show("Keyboard event detected.");
            }
        }
    }

    //In order to properly stop the keyboard handler thread before closing, kbdEvent will be set.

    private void btnClose_Click(object sender, EventArgs e)
    {
        // Ready to close
        appClosing = true;
        kbdEvent.Set();
        Application.Exit();
    }
}

What's wrong?

0 Answers0