Reputation: 109
So I have a 2 form application. The first form you enter in a quote of the day and press a button that opens the second form with the text displayed in the label. You then press a button and the text continuously scrolls across the screen using an infinite loop. It obviously hangs the program. I want to be able to have the text sit there scrolling until someone wants to stop it with a button click or something... I'm pretty sure that you have to do it with a thread, I just am new and don't really know much about threading... Here is my infinite loop that I call with the button click...
private void StartScroll()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(label2.Text + " ");
while (true)
{
char ch = sb[0];
sb.Remove(0, 1);
sb.Insert( sb.Length , ch);
label2.Text = sb.ToString();
label2.Refresh();
System.Threading.Thread.Sleep(100);
}
}
Any help is appreciated!
Upvotes: 2
Views: 1101
Reputation: 4542
If you need your text scrooling through the form(if i understood you correctly),you can try this.TextSize is the size of the text,x represents the x axis of the form you can change this if you need.
System.Text.StringBuilder sb;
private int x,TextSize;
public Form1()
{
InitializeComponent();
sb = new System.Text.StringBuilder(label2.Text + " ");
x = this.ClientRectangle.Width;
TextSize = 16;
}
private void Button1_Click(object sender, EventArgs e)
{
timer1.Tag = sb.ToString();
timer1.Enabled = true;
}
void timer1_Tick(object sender, EventArgs e)
{
Form1_Paint(this,null);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
string str = timer1.Tag.ToString();
Graphics g = Graphics.FromHwnd(this.Handle);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.FillRectangle(Brushes.Black, this.ClientRectangle);
g.DrawString(str, new Font("Arial", TextSize), new SolidBrush(Color.White), x, 5);
x -= 5;
if (x <= str.Length * TextSize * -1)
x = this.ClientRectangle.Width;
}
and to stop the timer
private void Button2_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
Upvotes: 0
Reputation: 2769
Simply create a timer that ticks every 100ms. Example:
//Create a new timer that ticks every 100ms
var t = new System.Timers.Timer (100);
//When a tick is elapsed
t.Elapsed+=(object sender, System.Timers.ElapsedEventArgs e) =>
{
//what ever you want to do
};
//Start the timer
t.Start();
Upvotes: 1
Reputation: 111
Take a look at this site for the background worker. It's really easy to implement and should be able to take care of your issue.
http://www.dotnetperls.com/backgroundworker
Upvotes: 2