I am trying to make a rss news ticker which will display the text,the text need move from left to right
I made the the code and text is moving from left to
I've already posted an example of how to create a Marquee Label to animate text from top to bottom, by using a Timer
and overriding OnPaint
method of a custom draw control in this post: Windows Forms Top to Bottom Marquee Label.
In the following code, I've changed that example to animates the text horizontally from right to left or left to right. It's enough to set RightToLeft
property of the control to change the direction. Also don't forget to set AutoSize
to false
.
Example - Right to Left and Left to Right Marquee Label in Windows Forms
using System;
using System.Drawing;
using System.Windows.Forms;
public class MarqueeLabel : Label
{
Timer timer;
public MarqueeLabel()
{
DoubleBuffered = true;
timer = new Timer() { Interval = 100 };
timer.Enabled = true;
timer.Tick += Timer_Tick;
}
int? left;
int textWidth = 0;
private void Timer_Tick(object sender, EventArgs e)
{
if (RightToLeft == RightToLeft.Yes)
{
left += 3;
if (left > Width)
left = -textWidth;
}
else
{
left -= 3;
if (left < -textWidth)
left = Width;
}
Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
var s = TextRenderer.MeasureText(Text, Font, new Size(0, 0),
TextFormatFlags.TextBoxControl | TextFormatFlags.SingleLine);
textWidth = s.Width;
if (!left.HasValue) left = Width;
var format = TextFormatFlags.TextBoxControl | TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
{
format |= TextFormatFlags.RightToLeft;
if (!left.HasValue) left = -textWidth;
}
TextRenderer.DrawText(e.Graphics, Text, Font,
new Rectangle(left.Value, 0, textWidth, Height),
ForeColor, BackColor, format);
}
protected override void Dispose(bool disposing)
{
if (disposing)
timer.Dispose();
base.Dispose(disposing);
}
}
You are using hard coded values for the start and max value of x. From your question I think the text in the label has a dynamic length (correct?). If the text is of dynamic length the value of x should also be dynamic.
Also, x starts at -800. Then slowly grows to 800 and then it gets set to 4. This seems strange to me, if the first run started at -800, the second run may also need to start at -800.
Hope this somewhat helped you. If not, please provide more details (like why you chose -800, 800 and 4).