Countdown timer using System.Timers.Timer in WPF application [duplicate] - c#

How can I implement the following in my piece of code written in WPF C#?
I have a ElementFlow control in which I have implemented a SelectionChanged event which (by definition) fires up a specific event when the control's item selection has changed.
What I would like it to do is:
Start a timer
If the timer reaches 2 seconds then launch a MessageBox saying ("Hi there") for example
If the selection changes before the timer reaches 2 seconds then the timer should be reset and started over again.
This is to ensure that the lengthy action only launches if the selection has not changed within 2 seconds but I am not familiar with the DispatcherTimer feature of WPF as i am more in the know when it comes to the normal Timer of Windows Forms.
Thanks,
S.

Try this:
private int timerTickCount = 0;
private bool hasSelectionChanged = false;
private DispatcherTimer timer;
In your constructor or relevant method:
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1); // will 'tick' once every second
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
And then an event handler:
private void Timer_Tick(object sender, EventArgs e)
{
DispatcherTimer timer = (DispatcherTimer)sender;
if (++timerTickCount == 2)
{
if (hasSelectionChanged) timer.Stop();
else MessageBox.Show("Hi there");
}
}
Finally, to make this work, you just need to set the hasSelectionChanged variable when the selection has changed according to your SelectionChanged event.

I've figured the complete code out as such:
DispatcherTimer _timer;
public MainWindow()
{
_myTimer = new DispatcherTimer();
_myTimer.Tick += MyTimerTick;
_myTimer.Interval = new TimeSpan(0,0,0,1);
}
private void ElementFlowSelectionChanged(object sender, SelectionChangedEventArgs e)
{
_counter = 0;
_myTimer.Stop();
_myTimer.Interval = new TimeSpan(0, 0, 0, 1);
_myTimer.Start();
}
private int _counter;
public int Counter
{
get { return _counter; }
set
{
_counter = value;
OnPropertyChanged("Counter");
}
}
private void MyTimerTick(object sender, EventArgs e)
{
Counter++;
if (Counter == 2)
{
_myTimer.Stop();
MessageBox.Show(“Reached the 2 second countdown”);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler e = PropertyChanged;
if (e != null)
{
e(this, new PropertyChangedEventArgs(propertyName));
}
}

look here is the code of how to use DispatherTimer and you can add your own logic in it. that will depends on you..
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, object e)
{
// show your message here..
}

To use a DispatcherTimer:
private DispatcherTimer _timer;
public void StartTimer()
{
if (_timer == null)
{
_timer = new DispatcherTimer();
_timer.Tick += _timer_Tick;
}
_timer.Interval = TimeSpan.FromSeconds(2);
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Hi there");
_timer.Stop();
}
void SelectionChangedEvent()
{
StartTimer();
}

Related

Timer variable is null which is declared for countdown timer?

I have this code which is used for countdown in C#. I can't seem to find why my variable t is null. I tried this code on a separate project and it works well. I tried to incorporate it into another project and it says that variable t is null.
public partial class tracker : Form
{
System.Timers.Timer t;
int h1, m1, s1;
public tracker()
{
InitializeComponent();
}
private void tracker_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
btnLogin.Enabled = false;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectedText = DateTime.Now.ToString("MM/dd/yyyy\n");
richTextBox2.SelectedText = "Time In\n";
richTextBox3.SelectedText = DateTime.Now.ToString("HH:mm:ss\n");
richTextBox4.SelectedText = "\n";
richTextBox5.SelectedText = "\n";
}
}
You are getting error t as null, because t.Start() is calling before instantiation of Timer object t.
To solve this issue, either instantiate before t.start() or create an object inside the constructor.
Like
public tracker()
{
InitializeComponent();
//Here you can instantiate Timer class
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void tracker_Load(object sender, EventArgs e)
{
//Do NOT create object of Timer class here
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
...
}

Best way to run a background task with timer

The following code run a task which check, each 5 seconds, the status of a database. I had to use the BeginInvoke but I'm not sure is the best way to do:
public btnDatabaseStatus()
{
InitializeComponent();
if (!DesignerProperties.GetIsInDesignMode(this))
Global.LM.SetTraduzioniWindow(this);
Init();
DispatcherOperation dbStatDispatcher = null;
try
{
dbStatDispatcher = App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
Timer timer = new Timer(5000);
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}));
}
catch (Exception ex)
{
if (dbStatDispatcher != null) dbStatDispatcher.Abort();
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (App.Current!=null) App.Current.Dispatcher.BeginInvoke(new Action(() => { IsDbConnected = Dbs[0].IsConnected; }));
}
private void Init()
{
Dbs = null;
Dbs = Global.DBM.DB.Values.Where(d => d.IsExternalDB).ToList();
lstvDatabase.ItemsSource = Dbs;
}
I'm afraid concerning the closing of main application as sometimes the Dispatcher is null. Any hints to improve the code?
Forget about Dispatcher.BeginInvoke and System.Threading.Timer.
Use a WPF DispatcherTimer:
public btnDatabaseStatus()
{
InitializeComponent();
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += OnTimerTick;
timer.Start();
}
private void OnTimerTick(object sender, EventArgs e)
{
IsDbConnected = Dbs[0].IsConnected;
}
Or shorter:
public btnDatabaseStatus()
{
InitializeComponent();
var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Tick += (s, e) => IsDbConnected = Dbs[0].IsConnected;
timer.Start();
}
If the Tick handler is supposed to do some long-running task, you may declare it async:
private async void OnTimerTick(object sender, EventArgs e)
{
await SomeLongRunningMethod();
// probably update UI after await
}

Windows Phone - Increment a value

How can I increment a value per second, when I passed it from another page?
Here is some code , where I get the value from the previous page + I added the Timer.
The Problem is that the EventHandler that has to been created for the Tick, can t be set to OnNavigatedTo.
public partial class Page1 : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(.1) };
public Page1()
{
InitializeComponent();
this.timer.Tick += new EventHandler(OnNavigatedTo);
this.Loaded += new RoutedEventHandler(OnNavigatedTo);
}
private void ButtonToPage1(object sender, RoutedEventArgs e)
{
App app = Application.Current as App;
MessageBox.Show(app.storeValue);
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
int test = (int.Parse(QueryStr));
}
try this:
DispatcherTimer tmr;
int test;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
test = (int.Parse(QueryStr));
LoadTimer();
}
public void LoadTimer()
{
tmr = new DispatcherTimer();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
tmr.Interval = new TimeSpan(0, 0, 1);
tmr.Tick += tmr_Tick;
tmr.Start();
});
}
void tmr_Tick(object sender, EventArgs e)
{
test++;
TextBlock.Text = test.ToString();
}
It isn't clear why you can't just follow the tutorial linked in your comment. I guess you misunderstand it and tried to handle Tick event using OnNavigatedTo() method. Yes, that won't work and you aren't supposed to do so.
You're supposed to simply attach event handler method in OnNavigatedTo :
private int myNumber;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
myNumber = (int.Parse(QueryStr));
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
//attach event handler method for Tick event
newTimer.Tick += OnTimerTick;
//or attach anonymous method so you don't need OnTimerTick() method :
//newTimer.Tick += (o, e) => { myNumber++; };
newTimer.Start();
}
void OnTimerTick(Object sender, EventArgs args)
{
myNumber++;
}

Window service : How to start a Timer at Particular Time

I have seen similar post of setting Timer at particular time ... I Dont want to run timer Whole Day ...I Want to start it at specific Time ..
Most of the suggestion is use Scheduled tasks ...but I want to do it with window service ....
Here is My Service Working Code :
public AutoSMSService2()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
Timer checkForTime = new Timer(5000);
checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
checkForTime.Enabled = true;
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
}
protected override void OnStop()
{
eventLog1.WriteEntry("In onStop.");
}
void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
eventLog1.WriteEntry("Timer Entry");
}
My Timer is working fine and adding Log at 5 sec interval ..But I want to start Timer Lets Say 3:00 PM ...
private static void SetTimer(Timer timer, DateTime due)
{
var ts = due - DateTime.Now;
timer.Interval = ts.TotalMilliseconds;
timer.AutoReset = false;
timer.Start();
}
But I am not sure How to Implement it in Code ..
Any suggestion would be Helpful
If you want to do it every day, Hope this will help.
private System.Threading.Timer myTimer;
private void SetTimerValue ()
{
DateTime requiredTime = DateTime.Today.AddHours(15).AddMinutes(00);
if (DateTime.Now > requiredTime)
{
requiredTime = requiredTime.AddDays(1);
}
myTimer = new System.Threading.Timer(new TimerCallback(TimerAction));
myTimer.Change((int)(requiredTime - DateTime.Now).TotalMilliseconds, Timeout.Infinite);
}
private void TimerAction(object e)
{
//here you can start your timer!!
}
here an example with windows form but you can achieve the some thing with windows service
public partial class Form1 : Form
{
private bool _timerCorrectionDone = false;
private int _normalInterval = 5000;
public Form1()
{
InitializeComponent();
//here you calculate the second that should elapsed
var now = new TimeSpan(0,DateTime.Now.Minute, DateTime.Now.Second);
int corrTo5MinutesUpper = (now.Minutes/5)*5;
if (now.Minutes%5>0)
{
corrTo5MinutesUpper = corrTo5MinutesUpper + 5;
}
var upperBound = new TimeSpan(0,corrTo5MinutesUpper, 60-now.Seconds);
var correcFirstStart = (upperBound - now);
timer1.Interval = (int)correcFirstStart.TotalMilliseconds;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// just do a correction like this
if (!_timerCorrectionDone)
{
timer1.Interval = _normalInterval;
_timerCorrectionDone = true;
}
}

Windows Store Application Metronome Stop Button Not Working

Hello there i am developing Windows Store App.
First of all, here is my code:
public class TickArgs : EventArgs
{
public DateTime Time { get; set; }
}
public class Metronome
{
private DispatcherTimer _timer;
public event TickHandler Tick;
public delegate void TickHandler(Metronome m, TickArgs e);
public Metronome()
{
_timer = new DispatcherTimer();
_timer.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, object e)
{
if (Tick != null)
{
Tick(this, new TickArgs { Time = DateTime.Now });
}
}
public void Start(int bbm)
{
_timer.Stop();
_timer.Interval = TimeSpan.FromSeconds(60 / bbm);
_timer.Start();
}
public void Stop()
{
_timer.Stop();
_timer.Start();
}
}
public class Listener
{
public void Subscribe(Metronome m, MediaElement mmx)
{
m.Tick += (mm, e) => mmx.Play();
}
public void UnSubscribe(Metronome m, MediaElement mmx)
{
m.Tick += (mm, e) => mmx.Stop();
}
}
To start metronome i use these codes:
l.Subscribe(m, mediaelement);
m.Start(120);
This works perfectly fine.
To stop metronome i use these codes:
l.UnSubscribe(m, mediaelement);
m.Stop();
Metronome stops BUT if i try to start again, it just does not start. What should i do?
I would appreciate your helps.
My regards...
Okay, so what you have done is you've subscribed your metronome to two handlers, each happening on the tick timer.
First of all, make a static method in your Listener class as the event handler that you can remove.
private static void TickPlay(object sender, EventArgs e)
{
mmx.Play();
}
Then, in your Subscribe method, just say:
m.Tick += TickPlay;
Lastly, for your Unsubscribe method, say:
m.Tick -= TickPlay;
This way it won't keep going Play/Stop ever tick interval.
I found the solution.
I've just made small changes in start and stop methods:
public void Start(int bbm)
{
_timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
_timer.Start();
}
public void Stop()
{
_timer.Stop();
}
Now it works perfectly fine.
Regards

Categories

Resources