1

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

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

原始问题

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

[使用块省略。目前使用 SlimDX 进行 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();
    }
}

怎么了?

4

0 回答 0