从DirectInput接收键盘通知(C#)

时间:2014-06-05 08:56:06

标签: c# directinput

编辑:我似乎找到了原因。我刚刚忘记在启动线程之前获取键盘设备。幸运的是,这是一个简单的问题。添加kbd.Acquire()之后;在线程调用之前,代码开始工作。

当然会需要相应的kbd.Unacquire();在关闭按钮的处理程序中。

原始问题

我是DirectInput和线程新手。有人可以指导我下面的代码中有什么错误。似乎我从来没有得到任何会触发我的事件处理程序线程的通知。

[省略使用块。目前使用SlimDX for DirectInput]

主窗体类包含所需变量的定义。

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();
    }
}

出了什么问题?

0 个答案:

没有答案