Jump to content

How to call one Timer from another Timer in C#?

Shammikit

So this is what i want to do. i want to move a picture box from left to right. the timer1 will move picturebox by 50 every millisecond and i want to move it by 50 every millisecond for five seconds and stop by using timer1.Enabled = false; . i want to make a timer2 and set its interval to 5 seconds and then call timer1 in it but i dont know how to do it. i have tired the code below and it failed 

//i tried calling it like this but i get this error: There is no argument given that corresponds to the required formal parameter 'sender' of 'Home.timer1_Tick(object, EventArgs)'	

//i think it wants me to pass some arguments but i dont know what kind of arguments that should be passed

private void timer2_Tick(object sender, EventArgs e)
 {
 Home h = new Home();
 h.timer1_Tick();
   
 }

 

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, Erik Sieghart said:

You're calling this method from an event off of the form or another place in the code?

another place in the form and in same class

Link to comment
Share on other sites

Link to post
Share on other sites

13 hours ago, Shammikit said:

another place in the form and in same class

If I understood you correctly, then you have something like the below example where both timers are running in the same form?

 

If this is the case, then timer2 should only need to stop timer1, not call timer1_Tick. Timer1 will call it's own tick event itself. And you don't need to create any sort of object to to access timer1 like you're doing with the Home class.

public class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        // Start timer1 and timer2
        timer1.Enabled = true;
        timer2.Enabled = true;
        // I'm not sure where you start the timers in your code. It could be in the designer properties.
        // It could be in a button click event. etc. It doesn't really matter so long as they are started at the same time.
        // I just put the code int the Form Load event for the sake of this example.
    }
  
    private void timer1_Tick(object sender, EventArgs e)
    {
        // Move picturebox here
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        timer1.Enabled = false; // Will stop timer1.
        timer2.Enabled = false; // If you also want to stop timer 2 from continuing to run
    }
}

Just make sure that each timer is set to the proper interval (50 ms for timer1 and 5000 ms for timer2)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×