C# - 事件后获取键盘输入

时间:2014-11-01 18:30:04

标签: c# visual-studio-2010 events input keyboard

所以我有一个HCI课程的任务,我可以解决所有问题但只有一部分。这是实际问题:

  

在主窗体上放下一个面板并更改其颜色。当用户输入“r”然后输入   数字n将面板向右移动n个像素。如果用户输入“l”然后输入a   number,n,将面板向左移动n个像素。

我挣扎的是在第一次击键后捕获整数。即," r"按下,我怎么能得到随后的输入?到目前为止,这是我的事件处理程序:

        private void rightLeftForm_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode.ToString() == "R")
        {
            //Move panel to the right

        }

        else if (e.KeyCode.ToString() == "L")
        {
            //Move panel to the left
        }
    }

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以尝试记住用户按下了哪个键“L”或“R”并存储此信息。下次使用数字键调用键处理程序时,您可以根据您存储的状态执行操作。

示例:

// enum to store panel movement direction
public enum PanelMovement
{
    None;
    Left;
    Right;
}

// member variable to store last panel movement
private PanelMovement mCurrentMovement = PanelMovement.None;

private void rightLeftForm_KeyDown(object sender, KeyEventArgs e)
{
        if (e.KeyCode.ToString() == "R")
        {
            // store direction after player has pressed "R"
            mPanelMovement = PanelMovement.Right;
        }
        else if (e.KeyCode.ToString() == "L")
        {
           // store direction after player pressed "L" 
           mPanelMovement = PanelMovement.Left;
        }
        // react on number key pressed
        else if(e.KeyCode >= Keys.D1 && e.KeyCode <= Keys.D9)
        {
            if(mPanelMovement == PanelMovement.Left)
               // move panel left
            else if(mPanelMovement == PanelMovement.Right)
              // move panel right
        }
    }