有人能告诉我如何用按键停止这个do-while循环吗?
我想做一个"移动"光标在我的控制台窗口中。
do
{
if (KeyInput.Key == ConsoleKey.UpArrow)
{
downup = downup++;
}
else if (KeyInput.Key == ConsoleKey.DownArrow)
{
downup = downup-1;
}
else if (KeyInput.Key == ConsoleKey.LeftArrow)
{
leftright = leftright -1;
}
else if (KeyInput.Key == ConsoleKey.RightArrow)
{
leftright = leftright++;
}
} while (KeyInput.Key != ConsoleKey.Escape);
答案 0 :(得分:2)
这应该这样做:
do
{
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.UpArrow)
{
downup++;
}
else if (key == ConsoleKey.DownArrow)
{
downup -= 1;
}
else if (key == ConsoleKey.LeftArrow)
{
leftright -= 1;
}
else if (key == ConsoleKey.RightArrow)
{
leftright++;
}
} while (key != ConsoleKey.Escape);
考虑到您的原始代码,我怀疑问题是您已经在循环之外(未发布)的代码从控制台读取密钥;这里的重要变化是,这需要在循环内部发生。
答案 1 :(得分:0)
所以你的意思是这样的?
do {
int downup, leftright;
downup = 10;
leftright = 10;
Console.SetCursorPosition(downup, leftright);
Console.Write("█");
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.UpArrow)
{
downup++;
}
else if (key == ConsoleKey.DownArrow)
{
downup -= 1;
}
else if (key == ConsoleKey.LeftArrow)
{
leftright -= 1;
}
else if (key == ConsoleKey.RightArrow)
{
leftright++;
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
答案 2 :(得分:0)
var looping = true;
while(looping)
{
switch(Console.ReadKey(true).Key)
{
case ConsoleKey.UpArrow:
downup++;
break;
case ConsoleKey.DownArrow:
downup--;
break;
case ConsoleKey.LeftArrow:
leftright--;
break;
case ConsoleKey.RightArrow:
leftright++;
break;
case ConsoleKey.Escape;
looping = false;
break;
}
}