Here’s a quick tip for your Windows Forms status bars. I often need to display status messages when certain tasks complete. For example, if you’re working on an item and Save you want the status bar to let you know that the item was saved. However, I don’t want the statusbar continually stay with this caption, but eventually revert back to some default setting like Ready.
Here’s where the System.Threading.Timer class can come in real handy. Handy because it so nice and easy to use although you need to add another method usually to handle the special object parameter signature that the timer requires.
I usually add several methods to my forms that contain status bars. One to handle a straight message, one with no parameter (which reverts to the default message) and one that has a timeout on it in seconds:
public void StatusMessage(string Message)
{
if (Message == null)
this.Status.Panels[0].Text = "Ready";
else
this.Status.Panels[0].Text = Message;
this.Status.Refresh();
}
public void StatusMessage()
{
this.StatusMessage(null);
}
public void StatusMessage(string Message,int SecondsToClear)
{
if (SecondsToClear == 0)
SecondsToClear = 5;
this.StatusMessage(Message);
System.Threading.Timer TimeThread = new System.Threading.Timer( new TimerCallback( StatusMessage),null, SecondsToClear * 1000,0) ;
}
public void StatusMessage(object state) // For Timer Thread method
{
// *** capture instance where form is gone
try
{
this.BeginInvoke( new ThreadStart(this.StatusMessage),null);
}
catch {}
}
The last two are the ones of interest and you can see the use of the timer. First the method calls the StatusMessage() with the temporary message to be displayed. Then the timer is created by creating a TimerCallback() delegate and pointing it at the last method with the object parameter. A parameter of null is passed which causes StatusMessage to display the default message. Finally the Seconds are passed (in milliseconds. The last parameter determines the frequency of repeats for this timer in milliseconds with 0 meaning no repeats which effectively fires the timer once.
Notice the try/catch block in the last StatusMessage method – this is required in case you shut down the form while the timer is still active. Although you could attach the timer to the form and disable the timer by changing the next tick, it’s easier to let the timer event fire and just capture the failure when it occurs. Not as clean, but it keeps the interface leaner. Without this code you’d get failures when you close the form while timer ticks are still pending. Note that even though the form gets shut down, the method still gets fired.
With this stuff in place you can now easily display messages that are more temporary and clear out. I find that this applies to most operations on a form where everything eventually should revert back to ‘Ready’ messages.
Other Posts you might also like