views:

104

answers:

2

I just added some extra functionality to a Coding4Fun project. I have my project set up with an extra option to allow it to automatically change the background after X amount of time. X is set from a ComboBox. However, I know I've done this in a terrible way, as I have created a new timer class with System.Timers.Timer as a parent so when the static method in the ElapsedEventHandler is called, I'm able to get back to the form and call ChangeDesktopBackground().

What is a better way to call ChangeDesktopBackground() at a user defined interval?

Here is my current solution, which involves me casting the sender as my inherited timer, which then gets a reference to the form, which then calls the ChangeDesktopBackground method.

private static void timerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    ((newTimer)sender).getCycleSettingsForm().ChangeDesktopBackground();
}

Edit:Added coding sample to show current solution

A: 

Timers are probably the most straight-forward way of doing it, although I'm not sure you're using a timer correctly. Here's how I've used timers in my projects:

// here we declare the timer that this class will use.
private Timer timer;

//I've shown the timer creation inside the constructor of a main form,
//but it may be done elsewhere depending on your needs
public Main()
{

   // other init stuff omitted

   timer = new Timer();     
   timer.Interval = 10000;  // 10 seconds between images
   timer.Tick += timer_Tick;   // attach the event handler (defined below)
}


void timer_Tick(object sender, EventArgs e)
{
   // this is where you'd show your next image    
}

Then, you'd connect your ComboBox onChange handler such that you'd be changing timer.Interval. I hope this helps!

Charlie Salts
A: 

I've written something like this before myself. System.Timers.Timer is overkill for this. You should probably use System.Windows.Forms.Timer, for a couple of reasons:

  1. You're doing something that doesn't have to be too precise. The Windows timer is just a WM_TIMER message sent to your windows app's message pump, so you're not getting super great precision, but changing your wallpaper once a second is unrealistic. (I wrote mine to change every 6 hours or so)
  2. When using a Windows Forms app that does some kind of timer-based task, you're going to run into all kinds of thread affinity issues if you go with System.Timers.Timer. Any Windows control has an affinity for the thread on which it was created, meaning that you can only modify the control on that thread. A Windows.Forms.Timer will do all that stuff for you. (For future nitpickers, changing wallpaper doesn't really count, cause it's a registry value change, but the rule holds generally)
ageektrapped