A small application inspired by Stefano Pranzo, to create a countdown to new year.
The final result is shown in the above image, to create it we have to create a new Windows Forms Application, rename its Form1 to FrmCountdown and change the following properties:
- BackgroundImage –>Choose an image from your disk using the 3 dots button and import it into the project resources. I’ve found the above one writing newyear on the bing image search.
- BackgroundImageLayout –> Stretch
- FormBorderStyle –> None
- KeyPreview –> True (we will use it to manage quit application).
We add a label to the form named lblCountdown with the following properties:
- BackColor –> transparent
- Font Name –> Lucida Calligraphy
- Font Size –> 64
- Forecolor –> Gold
- TextAlign –> MiddleCenter
We add a button to the form named btnClose with the following properties:
- UseVisualStyleBackColor –> False
- FlatStyle –> Flat
- BackColor –> transparent
- Font Name –> Lucida Calligraphy
- Forecolor –> Gold
- Text –> Close
We add to the form a timer named tmrCountdown.
The code behind the form is the following:
public FrmCountDown()
{
InitializeComponent();
tmrCountdown.Interval = 1000;
tmrCountdown.Enabled = false;
}
In the form constructor we set the timer to an interval of 1000 milliseconds.
private void FrmCountDown_Load(object sender, EventArgs e)
{
tmrCountdown.Start();
}
On the Load event of the form we activate the timer.
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
On the click event of the Close button we implement the application exit.
private void FrmCountDown_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
Application.Exit();
}
}
On the key Up event of the form we implement the application exit if Esc key is pressed.
DateTime mDtEnd = new DateTime(2011, 01, 01, 0, 0, 0);
We set a DateTime variable at form level with the final date and time, so 00:00:00 of january first.
private void tmrCountdown_Tick(object sender, EventArgs e)
{
TimeSpan sp = mDtEnd.Subtract(DateTime.Now);
this.lblCountdown.Text = sp.TotalHours.ToString("###") + ":" +
sp.Minutes.ToString("0#") + ":" + sp.Seconds.ToString("0#");
Application.DoEvents();
}
Finally on the Tick event of the timer we update our label calculating a difference between present date and time and the final date and time, converting then the data in a formatted string. As you can see we use the Subtract method of the DateTime class and the properties TotalHours, Minutes and Seconds of the Timespan representing the difference between the two dates.
Our NewYear Countdown is ready to go.
You can find the full project with working code in the resources area Cpde for Countdown
Happy newyear Everybody!
Technorati Tag:
DateTime,
Winforms