C# Tutorial - Adding Functionality to the Digital Clock


What happens when the digital clock is minimised to the system tray? The time disappears. So how can we overcome this? Easy, we show the time in the Text property of the form, this way, when the form is in the minimised state, the time will be displayed.

All this requires is a few simple changes to the code.

Firstly we want to draw on the minimised button in the task bar, so we need to know if it is minimised or not. FormWindowState.Minimized is set to true when the application is minimised, so we can check this against the WindowState property of the form.

We can perform this in the Timer_Tick method, so that it can be drawn accordingly.

private void timer1_Tick(object sender, EventArgs e)
{
  // See if application is minimised
  if (this.WindowState == FormWindowState.Minimized)
  {
    this.Text = GetTime();
  }
  else
  {
    label1.Text = GetTime();
  }

  Invalidate();
}

Secondly, so that the caption of the form is correct at the point of either minimising it or returning to the forms normal state, we can set the form's Text property in the SizeChanged event handler.

The SizeChanged event is raised if the Size property is changed by either a programmatic modification or user interaction with the form.

To create a handler for the SizeChanged event, follow using these steps.

  1. Highlight the form, by clicking on the caption bar.

  2. Click on the lightning bolt button at the top of the Properties Window to open the events pane.

  3. Double-click in the right hand column of the SizeChanged event. This will create an event handler in which we can add the following code.

private void Form1_SizeChanged(object sender, EventArgs e)
{
  // See if application is minimised
  if (this.WindowState == FormWindowState.Minimized)
  {
    this.Text = GetTime();
  }
  else
  {
    this.Text = "Clock";
  }

  Invalidate();
}

If you now build and run the application, when you minimise the clock, the time appears in the system tray instead of the word "Clock".


<< Previous Contents Next >>

© Publicjoe, 2008