我怎么能停止我的while循环?

Pet*_*ter 3 c#

我想在C#中使用以下代码,但我似乎无法摆脱它.如果用户按下某个键或移动啮齿动物(又称鼠标),我想终止该应用程序.这是我的代码(不笑!).

private void frmDots_KeyDown(object sender, KeyEventArgs e)
{
  bgNotClicked = false;
  Close();
}   

private void frmDots_Click(object sender, EventArgs e)
{
  bgNotClicked = false;
  Close();
}   



  while (bgNotClicked)
  {

    // Clear the first element in our XY position. This is the reverse of the way I   normally create the dots application
    System.Drawing.Rectangle clearDots = new System.Drawing.Rectangle(Dots.PositionX[iCounter], Dots.PositionY[iCounter], 8, 8);

    // Create the black color and brush to clear dots
    Color clearDotsColor = Color.Black;
    SolidBrush clearDotsBrush = new SolidBrush(clearDotsColor);

    // Finally clear the dot
    e.Graphics.FillEllipse(clearDotsBrush, clearDots);


    GetRandomPosition(iCounter);

    // Fill the elements to display colors on the displays canvas
    System.Drawing.Rectangle colorDots = new System.Drawing.Rectangle(Dots.PositionX[iCounter], Dots.PositionY[iCounter], 8, 8);

    // Create the color and brush to show dots
    Color colorRandom = GetRandomColor();
    SolidBrush colorBrush = new SolidBrush(colorRandom);

    // Finally show the dot
    e.Graphics.FillEllipse(colorBrush, colorDots);

    Thread.Sleep(5);

    iCounter++;
    if (iCounter == 399)
    {
      iCounter = 0;
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

Gar*_*ett 6

你的"忙碌等待"策略是糟糕的设计.相反,您应该使用被触发的事件处理程序:

  • 在按键上.
  • 移动鼠标时.

在任何一种情况下,您都可以通过终止申请来做出回应.