Introduction to WinForms – Scrolling Text in .NET (C#)

his tutorial shows how we can create a simple application to scroll user-input text, marquee-style, in C#.

This tutorial is an introduction to creating and coding WinForms in Visual Studio.NET. This simple program will allow you to enter text and then on the click of a button, the text will scroll until the program is closed. After learning the basics, there are more optimized ways of coding, and multi-threading can be incorporated into this program to make it more stable and user-friendly.

First, we add two labels, a text box and a button. One of the labels is where the scroll will take place, and the other is to simply tell the user to enter text into the text box. The Form should look something like this:

Next, we add logic to the TextChanged event of the text box. We can do this by double-clicking on the text box in design view. We will enable the button when text is entered, and disable the button on Form Load. The code will look something like this:

C#

0

1

2

3

4

5

6

7

8

9

10

11

12

13

privatevoidtextBox1_TextChanged(objectsender,EventArgse)

{

if(textBox1.Text.Trim()=="")

btnScroll.Enabled=false;

else

btnScroll.Enabled=true;

}

privatevoidForm1_Load(objectsender,EventArgse)

{

btnScroll.Enabled=false;

}

Next, we add logic to the Click event of the button. This code will call the method that causes the text to scroll: StartScroll(). The StartScroll method first adds a space at the end of the user-inputted string, and then loops until the program closes. The loop is constantly removing the last character in the string and putting it back at the start, giving it the illusion that the text is moving. After each loop, the thread is paused for 100 milliseconds, then repeats.