|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
OverviewThis application demonstrates how to create a "string loop" in C#. A common use of "string loops" is in web advertisements, where the slogan or product name appears to be revolving in a circle. The code creates a rectangle in the middle of the client area that is just large enough to fit the entire message, minus any trailing white space. Clicking on the form or resizing it will cause the "string loop" to restart. Points to NoticeRather than use a string to represent the message ("Catch Me If You Can…" ) it
is far more efficient and intuitive to use the private void DrawMovingText()
{
Graphics grfx = CreateGraphics();
Font font = new Font( "Courier New", 20, FontStyle.Bold );
string spaces = " ";
//
// StringBuilder is used to allow for efficient manipulation of
// one string, rather than generating many separate strings
//
StringBuilder str =
new StringBuilder( "Catch Me If You Can..." + spaces );
Rectangle rect = CreateRect( grfx, str, font );
int numCycles = str.Length * 3 + 1;
for( int i = 0; i < numCycles; ++i )
{
grfx.FillRectangle( Brushes.White, rect );
grfx.DrawString( str.ToString(), font, Brushes.Red, rect );
// relocate the first char to the end of the string
str.Append( str[0] );
str.Remove( 0, 1 );
// pause for visual effect
Thread.Sleep( 150 );
}
grfx.Dispose();
}
To avoid having //
// All of these events will restart the thread that draws
// the text
//
private void Form_Load( object sender, System.EventArgs e )
{
StartThread();
}
private void Form_MouseUp(object sender,
System.Windows.Forms.MouseEventArgs e)
{
StartThread();
}
private void Form_Resize( object sender, System.EventArgs e )
{
StartThread();
}
private void label_Click(object sender, System.EventArgs e)
{
StartThread();
}
private void StartThread()
{
thread.Abort();
// give the thread time to die
Thread.Sleep( 100 );
Invalidate();
thread = new Thread(new ThreadStart(DrawMovingText));
thread.Start();
}
The final point of interest is how the size and location of the rectangle that
contains the message are determined. The private Rectangle CreateRect
( Graphics grfx, StringBuilder str, Font font )
{
// + 5 to allow last char to fit
int w = (int)grfx.MeasureString(str.ToString(), font).Width + 5;
int h = (int)grfx.MeasureString( str.ToString(), font ).Height;
int x = (int)this.Width / 2 - w / 2;
int y = (int)this.Height / 2 - h;
return new Rectangle( x, y, w, h );
}
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||