
Introduction
While discussing how irritating a message box is displaying error messages and warnings (to us at least), I decided to write a simple control to display any relevant information to the user.
Background
The control was going to be very simple, just a label docked at the top of the window, with some properties to change the background color and message. But after using it in our app for a while, I realized most of our error messages were longer than the window! So, I set out to make it scroll.
Using the code
In a nutshell, the code works like this...
As the control is constructed, a timer starts, and status and message are set to "normal" and "", respectively. Every time the label is repainted (every time it changes), the event checks if the string actually fits in the label or not, and sets a flag accordingly. When the timer ticks, it checks the flag set by the Paint event, and if true, creates a new string, taking out the first char and saving it in a temporary variable, then adds the rest of the string to the new string variable, adding the char that used to be the first, last.
public partial class MessageBar : UserControl
{
private string status = "";
private string message = "";
char charTemp;
string tempMessage = "";
string myMessage = "";
bool scrollFlag = false;
public StatusBar()
{
InitializeComponent();
timer1.Start();
this.Status = "normal";
this.Message = "";
}
public void scrollText()
{
if (scrollFlag == true)
{
myMessage = lblMessage.Text;
if ((myMessage.Length == 0) != true)
{
charTemp = myMessage[0];
for (int i = 0; i < myMessage.Length - 1; i++)
{
tempMessage += myMessage[i + 1];
}
tempMessage += charTemp;
Message = tempMessage;
tempMessage = "";
}
}
}
public string Status
{
get
{
return status;
}
set
{
status = value;
if (status == "error")
{
lblMessage.BackColor = System.Drawing.Color.Red;
lblMessage.ForeColor = System.Drawing.Color.White;
}
else if (status == "warning")
{
lblMessage.BackColor = System.Drawing.Color.Yellow;
lblMessage.ForeColor = System.Drawing.Color.Black;
}
else if (status == "normal")
{
lblMessage.BackColor = System.Drawing.SystemColors.Control;
lblMessage.ForeColor = System.Drawing.Color.Black;
}
else
{
lblMessage.BackColor = System.Drawing.Color.Black;
lblMessage.ForeColor = System.Drawing.Color.White;
lblMessage.Text = "An Internal Error Has Occured (StatusBar.Status)";
}
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
lblMessage.Text = message;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
scrollText();
}
private void lblMessage_Paint(object sender, PaintEventArgs e)
{
if (lblMessage.Width < e.Graphics.MeasureString(lblMessage.Text,
lblMessage.Font).Width)
{
scrollFlag = true;
}
else
{
scrollFlag = false;
}
}
}
History
None... yet!