そこで、キープレス イベントを読み取り、キーストロークを文字列に記録するメソッドを作成したいと考えています。文字列の先頭に「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;
}