Click here to Skip to main content
6,629,377 members and growing! (20,972 online)
Email Password   helpLost your password?
Desktop Development » Miscellaneous » General     Intermediate License: The Code Project Open License (CPOL)

A marquee control in C#

By Josh Smith

A marquee control written in C#
C#, Windows, .NET 1.0, Dev
Posted:19 Feb 2003
Views:86,222
Bookmarked:27 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 3.59 Rating: 3.14 out of 5
2 votes, 14.3%
1
4 votes, 28.6%
2
4 votes, 28.6%
3
3 votes, 21.4%
4
1 vote, 7.1%
5

Overview

This 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 Notice

Rather than use a string to represent the message ("Catch Me If You Can�" ) it is far more efficient and intuitive to use the StringBuilder class, found in the System.Text namespace. StringBuilder allows you to directly manipulate a string, rather than having to make copies of a regular string. The manipulation of the StringBuilder�s internal string is quite straightforward:

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 DrawMovingText() eat up all of the CPU's attention it is placed on a worker thread. Every time the user clicks on the form or resizes it, the thread is killed and reborn. Obviously, if you wanted to alter the speed at which the letters "move" you would simply adjust the number of milliseconds that the thread sleeps for.

//

// 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 Graphics class has a MeasureString method that will give you the width or height of the string that you are passing in. Those are used for the width and height of the rectangle. You then use those values in tandem with the dimensions of the form to determine the coordinates of where the rectangle will originate from.

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 );
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Josh Smith


Member
Josh creates software, mostly with C# and XAML.

He works at IdentityMine as a Senior UX Developer.

He plays the music of J.S. Bach on the piano, but has started branching into other composers recently.

Get his runtime debugging and scripting tool, called Crack.NET, right here[^].

Download his WPF.JoshSmith library here[^]

You can check out his WPF blog here[^].

You can take his guided tour of WPF here[^].

You can check out a powerful debugger visualizer he worked on called Mole for Visual Studio here[^].

His Microsoft MVP profile can be viewed here[^].
Occupation: Software Developer (Senior)
Company: IdentityMine, Inc.
Location: United States United States

Other popular Miscellaneous articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
QuestionTransparent background of rectangle PinmemberMember 273427019:45 22 Jun '09  
AnswerRe: Transparent background of rectangle Pinmemberrootjumper23:22 17 Sep '09  
Generalthumbs up Pinmembernelsonpaixao14:35 1 Aug '08  
GeneralWidth of scrolling text. PinmemberDivermarv13:44 27 Aug '04  
GeneralRe: Width of scrolling text. PinmemberIcemanlaw5:34 30 Jan '05  
GeneralThread.Join PinmemberThong Nguyen18:23 20 Feb '03  
GeneralRe: Thread.Join PinmemberThong Nguyen18:26 20 Feb '03  
GeneralRe: Thread.Join PinmemberMichael Potter3:53 21 Feb '03  
GeneralRe: Thread.Join Pinmemberleppie7:12 21 Feb '03  
GeneralRe: Thread.Join PinmemberMichael Potter7:51 21 Feb '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Feb 2003
Editor: Nishant Sivakumar
Copyright 2003 by Josh Smith
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project