Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to work with time-driven events in WPF

Tags:

.net

wpf

timer

I have a simple app, that has media element in it, and it plays some movies, one after another. I want to have a 15 seconds delay between one movie stops playing, and the next one starts. I'm new to WPF and though I know how to do this the old (WinForms) way with a Timer and control.Invoke, I thought that there must be a better way in WPF. Is there?

like image 619
Krzysztof Kozmic Avatar asked Oct 14 '22 17:10

Krzysztof Kozmic


1 Answers

The DispatcherTimer is what you want. In this instance you'd create a DispatcherTimer with an interval of 15 seconds, kick off the first video. Then when that video has completed enable the timer and in the tick event show the next video, and set the timer to disabled so it doesn't fire every 15 seconds. DispatcherTimer lives in the System.Windows.Threading namespace.

DispatcherTimer yourTimer = new DispatcherTimer();

yourTimer.Interval = new TimeSpan(0, 0, 15); //fifteen second interval
yourTimer.Tick += new EventHandler(yourTimer_Tick);
firstVideo.Show();

Assuming you have an event fired when the video is finished then set

yourTimer.Enabled = True;

and then in the yourTimer.Tick event handler

private void yourTimer_Tick(object sender, EventArgs e)
{
    yourTimer.Enabled = False;//Don't repeat every 15 seconds
    nextVideo.Show();
}
like image 62
MrTelly Avatar answered Oct 18 '22 22:10

MrTelly