所以我想制作一个方法来读取按键事件,然后将击键记录到一个字符串中。这个想法是字符串包含前导“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;
}