On Keypress读取多个按键事件



所以我想制作一个方法,读取按键事件,然后将按键记录到字符串中。其思想是,字符串包含前导的"R"或"L",后跟2个整数。然而,当我在MoveBox方法中显示"MoveDist"字符串变量时,它总是同一个按键重复3次,而不是在每次笔划后重新轮询键盘。例如,当我运行调试并输入"R"时,程序崩溃,因为输入字符串立即变为"rrr"。有人有解决方案吗?

void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    String input = "";
        if (e.KeyChar == 108)
        {
            input = "l";
        }
        else if (e.KeyChar == 114)
        {
            input = "r";
        }
        else if (e.KeyChar >= 48 && e.KeyChar <= 57)
        {
            int charPress = e.KeyChar - 48;
            input = input + charPress.ToString();
        }
    Form1_MoveBox(input);
}
void Form1_MoveBox(String newInput)
{
    String input = "";
    while (input.Length <= 3)
    {
        input = input + newInput;
    }
    String moveDist = input.Substring(1, 3);
    MessageBox.Show(moveDist);
    int distance = Int32.Parse(moveDist);
    if (input.Substring(0, 1) == "l")
    {
        int x = panel1.Location.X - distance;
        int y = panel1.Location.Y;
        panel1.Location = new Point(x, y);
        panel1.Visible = true;
    }
    else if (input.Substring(0, 1) == "r")
    {
        int x = panel1.Location.X + distance;
        int y = panel1.Location.Y;
        panel1.Location = new Point(x, y);
        panel1.Visible = true;
    }

使用KeyUp而不是KeyPress,因为通常情况下,您应该在应用程序中处理KeyUp事件。在用户释放键之前,不应在UI中启动操作。

在这种情况下,发射事件的顺序是

  1. KeyDown(一次)
  2. KeyPress(直到按键被按下,并基于操作系统对键盘延迟和重复率的设置)
  3. KeyUp(一次)

当用户长时间按住按键时,可以通过在KeyDown中将布尔值设置为true,然后在KeyUp上将其设置为false来防止KeyPress多次触发,但KeyUpKeyDown的优点是,无论用户按住按键多长时间,它们都只会触发一次,并且可以避免"rrrrrrrrr"。

使用KeyUp的另一个好处是,您有许多关于用户输入的附加信息,比如按下Alt、Ctrl或Shift,或者事件的ControlKeyCode属性,您可以使用它并将其与Keys进行比较,以避免在代码中使用某种e.KeyChar == 108,并使其更像e.KeyCode == Keys.R一样可读。

如果您按住键,按键事件也会触发。因此,如果你按下r键,它很可能会多次开火。对于这个事件,最好使用keydown事件。当你按下r键时,它只会发射一次,但如果你按住键,它不会继续发射。

最新更新