This example combines the techniques from the following two posts:
This example uses two settings, LastLoadTime and LastUrl, to determine whether it is a new day and whether the image URL has changed.
Normally I try keep examples simple enough that you don’t need a flow chart to understand how they work, but in this example the following flow chart will probably help.
When the program starts, it compares the LastLoadTime setting to the current day to see if it is a new day. If it is not a new day, then the program waits until the following day (ten minutes after midnight) before it tries to download a new Astronomy Picture of the Day.
If it is a new day, the program downloads the Astronomy Picture of the Day web page as in the example Download the Astronomy Picture of the Day in C#. It gets the URL for the day’s image and compares it to the LastUrl setting.
If the new image URL is the same as the last one we displayed, then the Astronomy Picture of the Day page hasn’t been updated for the new day.
I don’t know what time the new image is posted or even the Astronomy Picture of the Day server’s time zone. In fact, I don’t want to know. If the program knew that, then it would depend on those values so it would need to be updated if the Astronomy Picture of the Day site changed.
Rather than trying to figure out when the new picture will be available, the program just waits ten minutes and tries again.
Eventually the program finds a new image URL so it displays the new picture on the desktop as in the example Set the Windows desktop picture in C#. It updates the LastLoadTime and LastUrl settings and then waits until the next day to start over.
In theory you should be able to leave this program running and it will update the desktop background to show the new Astronomy Picture of the Day every day. (Although I haven’t had it running long enough to know how it will behave over a long period off time.)
The program uses a Timer named tmrDownload to wait until the next day or to wait for ten minutes.
Download the example program to see the code and additional details.
A quick note on timers and putting your computer to sleep. Suppose the Timer tmrDownload is waiting for 12:10 AM tomorrow and you put your system to sleep. Now suppose you wake the system up at 8:00 AM the next day. When the system wakes, the Timer reanimates and notices the current time. The Timer realizes that its time is up, so it fires its Tick event. More precisely the event fires when the system wakes up and not when you log in.
In this example the event doesn’t fire at the time when the program expected, but in this example at least that doesn’t matter. The program realizes that it’s a new day and tries to load the new Astronomy Picture of the Day as desired.