简体   繁体   中英

c# counting clicks

I have a timer and in 30 minutes I want to count clicks and show it in a textbox. but how? here is timer code:

decimal sure = 10;
private void button1_Click(object sender, EventArgs e)
{
  button1.Enabled = true;
  timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
  sure--;
  label3.Text = sure.ToString();
  if (sure == 0) 
  {
    timer1.Stop();
    MessageBox.Show("Süre doldu");
  }
}

Declare your clickCounter at global, and raise your counter++ in Mouse Click Event. If you do it more specific, you can use Background Worker, to track time. and use Application.DoEvents() to write remaining to to textBox Put a button, 2 labels, and a timer. rename labels with lblClickCount and lblRemainingTime

private int clickCounter = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        clickCounter++;
        lblClickCount.Text = clickCounter.ToString();
    }

    decimal sure = 10;
    private void timer1_Tick(object sender, EventArgs e)
    {
        sure--;
        lblRemainingTime.Text = sure.ToString();
        Application.DoEvents();
        if (sure == 0)
        {
            timer1.Stop();
            MessageBox.Show("Süre doldu. Toplam tiklama sayisi:" + clickCounter.ToString());
        }
    }

If you wanted to reuse buttoN1 to count the clicks but not Start new timer you can add a if around the code you want to protect.

bool hasTimerStarted = false;
int numberOfClicks = 0;
private void button1_Click(object sender, EventArgs e)
{
  if(!hasTimerStarted)
  {
      button1.Enabled = true;
      timer1.Start();
      hasTimerStarted = true;
  }
  ++numberOfClicks;
}

When the timer expires you reset the count and if the timer has started.

private void timer1_Tick(object sender, EventArgs e)
{

    TimeSpan ts = stopWatch.Elapsed;

    // Format and display the TimeSpan value.
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);

    label3.Text = elapsedTime;
    labelClicks.Text = "User clicked " + clicksNo.toString() + "nt times..";

    if (stopWatch.ElapsedMilliseconds >= this.minutes * 60 * 1000) 
    {
        timer1.Stop();
        MessageBox.Show("Time elapsed.");
        hasTimerStarted = false;
        numberOfClicks = 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM