Ronald Jeremiah
Ronald Jeremiah

Reputation: 65

Text animation in Windows Forms

I was wondering if there was a way of adding a sort of animation to text displayed on a form.

What I had in mind when I thought of this was kind of similar to what you can do with text in PowerPoint (i.e. a typewriter-like animation where the text is typed one at a time, have the whole textbox appear with a certain effect etc), I'm just looking to find out what you can do using Windows Forms.

Currently I'm using a textbox to display information on my form application, though in hindsight I realise labels would have worked just as well.

EDIT: Turns out I was using labels after all, I just gave it a name with 'textbox' inside for lack of a better description.

Upvotes: 3

Views: 16201

Answers (2)

jrob
jrob

Reputation: 532

public partial class Form1 : Form
{
    int _charIndex = 0;
    string _text = "Hello World!!";
    public Form1()
    {
        InitializeComponent();
    }

    private void button_TypewriteText_Click(object sender, EventArgs e)
    {
        _charIndex = 0;
        label1.Text = string.Empty;
        Thread t = new Thread(new ThreadStart(this.TypewriteText));
        t.Start();
    }

    private void TypewriteText()
    {
        while (_charIndex < _text.Length)
        {
            Thread.Sleep(500);
            label1.Invoke(new Action(() =>
            {
                label1.Text += _text[_charIndex];
            }));
            _charIndex++;
        }
    }
}

Upvotes: 4

itsmatt
itsmatt

Reputation: 31416

Now, I personally wouldn't do this because gratuitous animations tend to annoy users. I'd only use animation sparingly - when it really makes sense.

That said, you can certainly do something like:

 string stuff = "This is some text that looks like it is being typed.";
 int pos = 0;
 Timer t;

 public Form1()
 {
     InitializeComponent();
     t = new Timer();
     t.Interval = 500;
     t.Tick += new EventHandler(t_Tick);
 }

 void t_Tick(object sender, EventArgs e)
 {
     if (pos < stuff.Length)
     {
         textBox1.AppendText(stuff.Substring(pos, 1));
         ++pos;
     }
     else
     {
         t.Stop();
     }
 }

 private void button1_Click(object sender, EventArgs e)
 {
     pos = 0;
     textBox1.Clear();
     t.Start();
 }

or something like that. It'll tick off ever half second and add another character to the multi-line text box. Just an example of what someone could do.

Upvotes: 1

Related Questions