Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop my while loop?

Tags:

c#

I would like to use the following code in C# but I just can't seem to get out of it. I would like to terminate the application if the user presses a key or moves the rodent (aka mouse). Here is my code (no laughing!).

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;
    }

  }
}
like image 825
Peter Avatar asked Mar 07 '26 08:03

Peter


1 Answers

Your "busy waiting" strategy is poor design. Instead, you should use event handlers that are fired:

  • On keypress.
  • When the mouse is moved.

In either case, you can respond by terminating the application.

like image 124
Garrett Avatar answered Mar 08 '26 21:03

Garrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!