Reputation: 1476
private void btnProveri_Click(object sender, EventArgs e)
{
lblRezultat.Text = DateTime.Now.ToString();
timer1.Interval = 1800;
timer1.Start();
MessageBox.Show(DateTime.Now.ToString());
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1800;
}
I am a newbie trying to learn timers and this is my code above. I want to make a Timer which last 1,8 seconds. Then I call it inside the button when it's clicked and the first time the label is set to specific date and then i set interval to the timer and start it, but the messagebox outputs the same time (no delay at all).
Upvotes: 0
Views: 2161
Reputation: 2295
It looks like you want to do something like this:
private void btnProveri_Click(object sender, EventArgs e)
{
lblRezultat.Text = DateTime.Now.ToString();
var timer = new System.Timers.Timer(1800);
timer.Start();
timer.Elapsed += timer1_Tick;
}
private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
MessageBox.Show(DateTime.Now.ToString());
}
Here is working console example:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("App started");
var timer = new System.Timers.Timer(1800);
timer.Start();
timer.Elapsed += timerHandler;
Console.ReadLine();
}
private static void timerHandler(object sender, System.Timers.ElapsedEventArgs e)
{
Messenger(DateTime.UtcNow.ToString());
}
private static void Messenger(string time)
{
Console.WriteLine(time);
}
}
Upvotes: 0
Reputation: 881093
That's because you're displaying the message box from within the same code that creates the timer. Effectively:
buttonClick:
Populate some text field.
Start timer so that it calls timerTick in 1.8 seconds
Display message box
timerTick:
Restart timer so it calls this function in 1.8 seconds.
As you can see, the message box is displayed at the time you press the button, not when the timer fires. When the timer fires, all you do is set it to fire again in another 1.8 seconds, but you don't actually do anything else at that point.
If you want it to display after the timer fires, it will have to be done in the timer function timer1_Tick
. But you may want to be careful with that, it's possible you may end up with a rather large number of dialog boxes.
Upvotes: 3