2 svar
81 visningar
Sebastian123 1 – Fd. Medlem
Postad: 26 aug 2021 22:01 Redigerad: 2 sep 2021 14:52

Timern på min windows forms vill inte stoppa.

Timern på Winner funktionen vägrar att sluta ticka även om jag använder timer1.Stop(); 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Windows_forms
{
  public partial class Form1 : Form
  {
    int score;
    double timer = 0;


  public Form1()
  {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
  }

 

  private void Start_btn_Click(object sender, EventArgs e)
  {
    Random_location_btn.Visible = true;

    Point Btn_position = Location_randomizer();
    Start_btn.Visible = false;

    Random_location_btn.Location = Btn_position;
    timer1.Start();


  }


  public Point Location_randomizer()
  {
    int location_x;
    int location_y;

    Random rand = new Random();

    location_x = rand.Next(0, 890);
    location_y = rand.Next(0, 890);
    Point position = new Point(location_x, location_y);
    return (position);
  }

  private void Score_Label_Click(object sender, EventArgs e)
  {

  }

  private void Random_location_btn_Click(object sender, EventArgs e)
  {
    score++;
    Score_Label.Text = "score:" + " " + score;
    Point btn_position = Location_randomizer();

    Random_location_btn.Location = btn_position;

  }

  private void timer1_Tick(object sender, EventArgs e)
  {
    timer += 0.1;
    Time_label.Text = "Time:" + " " + timer;

    Winner();
  }

  private void Winner()
  {
    if (timer < 10 && score == 10)
    {
      MessageBox.Show("You won!");
      timer1.Stop();
      Random_location_btn.Enabled = false;
      timer = 0;
      score = 0;
    }
    else if (timer >= 10)
    {
      MessageBox.Show("You lost :(");
      timer1.Stop();

      Random_location_btn.Enabled = false;
      timer = 0;
    }
  
  }

  private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
  {
    timer = 0;
    timer1.Stop();
    Time_label.Text = "Time: " + " 0";
    Start_btn.Visible = true;
    Random_location_btn.Visible = false;
  }
}
Hilda 367 – Livehjälpare
Postad: 29 aug 2021 18:30 Redigerad: 29 aug 2021 18:31

Det är svårt att se, för du har inte tagit med koden där du definierar timer1. Troligast är att du har två olika namespaces med olika timer1, så att du stoppar en annan timer1 än den du startade. 

beerger 962
Postad: 29 aug 2021 19:16

Infoga det gärna som programmeringskod, så blir det betydligt enklare för oss att läsa.

Svara Avbryt
Close