Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Timer not stopping?

Tags:

c#

Here's what I have, why is my timer(s) not stopping? I'm not sure what I'm doing wrong. I'm fairly new to C# and I'm trying to make it so my splash screen Hides(form1) and my program starts(samptool) however my program starts but the splash screen stays and the timers reset instead of stopping. Every 6.5 seconds the application opens in a new window.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Timers;
namespace SplashScreen.cs
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            timer1.Interval = 250;
            timer2.Interval = 6500;
            timer1.Start();
            timer2.Start();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.progressBar1.Increment(5);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            SampTool w = new SampTool();
            Form1 m = new Form1();
            timer1.Enabled = false;
            timer1.Stop();
            timer2.Enabled = false;
            timer2.Stop();
            m.Hide();
            w.Show();
        }
    }
}
like image 923
Lynnstrum Avatar asked Dec 05 '25 14:12

Lynnstrum


1 Answers

When you use the new keyword, you create a new instance of a class:

Form1 m = new Form1();

When you create a new instance, the constructor is invoked (the constructor is the method that is named the same as the class).
This will run all the code in the constructor again, hence creating new timers.

To close the current form, you should just run the forms Hide method:

private void timer2_Tick(object sender, EventArgs e)
{
    timer1.Stop();
    timer2.Stop();
    SampTool sampTool = new SampTool();
    sampTool.Show();

    Hide();  // call the Forms Hide function.
}
like image 162
Jite Avatar answered Dec 07 '25 04:12

Jite



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!