Winform application Timer doesn´t work correctly - c#

i´m doing a winform app, and the timer isn´t working fine. First time works, and then, it doesn´t.
Here is the code:
public void GetNewTurn(Turn turn)
{
_tmrStarTime = DateTime.Now;
timer1.Start();
timer1.Tick += tmr1_Tick;
}
private void tmr1_Tick(object sender, EventArgs e)
{
//timer code here
timer.stop();
}
So, the idea is:
GetNewTurn is a function which is invoked from another place. The first time which I invoke it, works fine, then doesn´t. I put a breakpoint inside the tmr1_Tick, and i can see that it just works the first time, then, doesn´t.
In the Timer properties, i set Enable = True.
What i´m doing wrong?
Thanks!

You shoudn't stop the tmr1_Tick in the first tick
public void GetNewTurn(Turn turn)
{
_tmrStarTime = DateTime.Now;
timer1.Start();
timer1.Tick += tmr1_Tick;
}
private void tmr1_Tick(object sender, EventArgs e)
{
//the code for each tick
}

Only add the handler once in the constructor or OnLoad override.
timer1.Tick += tmr1_Tick;
public void GetNewTurn(Turn turn)
{
_tmrStarTime = DateTime.Now;
timer1.Start();
}

Related

Refresh timer and warning boxes in c#

Basically, I have a frequency that refreshes data on screen. When one of these data points goes over a set value, it sets off an error. Upon this error setting off, I want the background colour to change (like a flashing warning).
The problem I have is that I am already using a timer, and when I call a new timer (for the flash) it stops the other timer working, and I'm unaware of how to call in the previous method (being as it uses object sender)
Here is my code:
public void Freq_Change(object sender, SelectionChangedEventArgs e)
{
_timer.Stop();
_timer.Interval = TimeSpan.FromSeconds(Freq.SelectedIndex + 1);
_timer.Start();
_timer.Tick += timer_Tick;
}
and timer_Tick
void timer_Tick(object sender, EventArgs e)
{
//Data generator
//Value pushes to text boxes
if (value is over 100)
{
Warning_Blink
"Oh no, an error"
}
else
{
"All good"
}
Warning_Blink has the new timer in, which then calls warning_Tick
In warning_Tick
private bool _warning = false;
private void warning_Tick(object sender, EventArgs e)
{
if (_warning)
{
ErrorBox.Background = new SolidColorBrush(Colors.Red);
}
else
{
ErrorBox.Background = new SolidColorBrush(Colors.White);
}
_warning = !_warning;
Freq_Change();
}
Here where I call Freq_Change (which doesn't work) I want to be able to go back to the old timer (or better yet never switch between the two) so the data generation can continue.
Can anyone help me with this? I've been scratching my head for hours

Timer Elapsed Event with Kinect SDK

So I'm using the Kinect SDK to make an application, and it's going well! I'm trying to make a button take a picture, but I want the code taking the picture to be delayed so the people have time to pose. I've tried using System.Threading.Thread.Sleep(3000); but what happens is that the whole thing freezes (Yes I know that's what sleep does...) and it uses the first frame anyway. So now I'm trying to use a Timer and Timed Event, but keep getting errors due to the inability to make it static (Kinect thing).
public class Timer1
{
private System.Timers.Timer aTimer;
public void Main()
{
aTimer = new System.Timers.Timer(3000);
//This is where the problem is. I'm getting "Cannot access a non-static member of outer type 'KinectButton.MainWindow' via nested type 'KinectButton.MainWindow.Timer1'
aTimer.Elapsed += new ElapsedEventHandler(takepicture);
aTimer.Interval = 1000;
aTimer.Enabled = True;
}
}
[private void takepicture(object sender, ElapsedEventArgs e)
{
BitmapSource image = (BitmapSource)videoStream.Source;
image.Save(DateTime.Now.ToString("ddMMyyyy HHmmss") + ".jpg", ImageFormat.Jpeg);
}
private void button7_Click(object sender, RoutedEventArgs e)
{
//Here I'm also getting "'KinectButton.MainWindow.Timer1' does not contain a definition for 'Enabled'"
Timer1.Enabled = true;
}
private void Timer1_Tick(object sender, EventArgs e)
{
//Here I'm getting "'KinectButton.MainWindow.Timer1' does not contain a definition for 'Enabled'" again...
Timer1.Enabled = false;
}
Well, let me know if you guys can help!
I assume this is a WPF app? I think you will want to use Windows.Threading.DispatcherTimer instead
Private timer As New Windows.Threading.DispatcherTimer
timer.Interval = New TimeSpan(0, 0, 0, 1)
AddHandler timer.Tick, AddressOf timer_Tick
timer.Start()
Private Sub timer_Tick(ByVal Sender As Object, ByVal e As EventArgs)
'do something
End Sub
yeah i know its vb but it should be easy to convert

how to increment the variable correctly?

when I start the timer ..timel is incremented normally ..but as soon as I stop the timer i.e. call the click_TimerStop function and start the timer again...the timel variable is incremented by timel+=2..and when I repeat the process ..it is increased by timel+=3..and it goes on and on ...how do I correct this ?..
DispatcherTimer clktimer = new DispatcherTimer();
private void click_TimerStart(object sender, RoutedEventArgs e)
{
clktimer.Start();
clktimer.Interval =new TimeSpan(0,0,1);
clktimer.Tick +=clktimer_tick;
}
private int timel = 0;
private void clktimer_tick(object sender, object e)
{
timel++;
timerSecond.Text = timel.ToString();
}
private void click_TimerStop(object sender, RoutedEventArgs e)
{
clktimer.Stop();
}
add
clktimer.Tick -=clktimer_tick;
before
clktimer.Tick +=clktimer_tick;
you'll unsubscribe and subscribe to event, so only one handler will be active at a time
and It's better to call start() after you set all settings to timer
It's because you're continually adding the clktimer_tick event handler each time you start the timer. Initialize your timer somewhere where it will only be called once and not every time you start, because there's no need to keep setting the same settings each time.

building a stop watch with help of timer

I want to add functionality to my WinForms so that when it starts a counter starts which will be in hh:mm. I know this can be done using a timer. I have made a time label which displays the current time, but I don't know how to start the timer when the form is loaded. Is there any method or class for that?
Place Timer component to your form (drag it from ToolBox - it's imporant, because timer should be registered as form's component to be disposed correctly when form closes). Set timer's Interval property to 60000 (that's equal to one minute). And subscribe to Tick event:
void timer1_Tick(object sender, EventArgs e)
{
if (endTime < DateTime.Now)
{
MessageBox.Show("Time is out!");
timer1.Stop();
return;
}
timeLabel.Text = (endTime - DateTime.Now).ToString(#"hh\:mm");
}
On Form_Load event handler start timer and save countdown end time:
private DateTime endTime; // field to store end time
void Form1_Load(object sender, EventArgs e)
{
endTime = DateTime.Now.AddMinutes(120); // set countdown to 120 minutes
timer1.Start();
}
The creation of a timer is very simple and straight forward:
Timer t1 = new Timer();
t1.Interval = 100;
t1.Tick+=new EventHandler(t1_Tick);
t1.Start();
void t1_Tick(object sender, EventArgs e)
{
}
For more information see http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.80).aspx

How to let System.Windows.Forms.Timer to run the Tick handler immediately when starting?

The Timer following is System.Windows.Forms.Timer
C# Code:
Timer myTimer = new Timer();
myTimer.Interval = 10000;
myTimer.Tick += new EventHandler(doSth);
myTimer.Start();
The timer will doSth every 10 seconds, but how to let it doSth immediately when starting?
I tried to create a custom timer which extends Timer, but I can't override the Start method.
For now, my code is:
myTimer.Start();
doSth(this, null);
I don't think it's good. How to improve it?
It's perfect. Don't change a thing.
I'm not sure of your exact requirements but why not put the code inside your timer callback inside another method?
e.g.
private void tmrOneSec_Tick(object sender, System.EventArgs e)
{
DoTimerStuff();
}
private void DoTimerStuff()
{
//put the code that was in your timer callback here
}
So that way you can just call DoTimerStuff() when your application starts up.
The timer has to have form level scope, and it's not clear that you have that. I whipped up a small example out of curiosity and it is working for me:
private void Form1_Load(object sender, EventArgs e)
{
txtLookup.Text = "test";
DoSomething();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
DoSomething();
}
private void DoSomething()
{
txtLookup.Text += "ticking";
}
Every 10 seconds it appends another "ticking" to the text in the textbox.
You say,
"The timer will doSth every 10 seconds, but how to let it doSth immediately when starting?"
I say, call doSth immediately before calling the timer's start method

Categories