位置:首页 > 软件编程 > C#笔记
C# 跑马灯效果的实现方法
日期:2023-01-04 人气:

大家好,对C# 跑马灯效果的实现方法感兴趣的小伙伴,下面一起跟随三零脚本的小编来看看C# 跑马灯效果的实现方法的例子吧。

跑马灯效果,功能效果大家应该都知道,就是当我们的文字过长,整个页面放不下的时候(一般用于公告等),可以让它自动实现来回滚动,以让客户可以看到完整的信息(虽然要多等一会儿时间)。

其实对于Winform这种技术,实现任何的动态效果相对来说都比较麻烦。

而且一般都需要搭配定时器使用,当然,这次要写的跑马灯效果也是一样的,使用了System.Timers.Timer来实现。

因为使用麻烦,所以要进行封装,所以要不断的造轮子(尽管是重复的),但重复也是一个加强记忆以及不断深入的过程,我认为这并不是多余的。因此,为了方便调用,还是用自定义控件封装一下属性,使用的时候只要设置属性即可。

代码如下:

/**
 * 跑马灯效果
 * @arrange (三零.脚本) www.q3060.com
 **/
public partial class CustomLable : Label
{
	System.Timers.Timer timer = new System.Timers.Timer(200);
	int offset = 5;//偏移量
	PointF textPoint;
	public CustomLable()
	{
		InitializeComponent();
		textPoint = new PointF(this.Width, 0);
		timer.Elapsed += (s, e) =>
		{
			try
			{
				if (!IsDisposed)
				{
					Graphics g = CreateGraphics();
					SizeF textSize = g.MeasureString(Text, Font);
					textPoint.X -= offset;
					if (textPoint.X <= -textSize.Width)
					{
						textPoint.X = Width;
					}
					g.Clear(BackColor);
					g.DrawString(Text,Font, new SolidBrush(ForeColor), textPoint);
				}
			}
			catch { }
		};
	}

	protected override void OnPaint(PaintEventArgs pe)
	{
		base.OnPaint(pe);
	}

	private bool _IsMarquee;

	[Browsable(true)]
	[Description("是否以跑马灯效果显示")]
	public bool IsMarquee
	{
		get { return _IsMarquee; }
		set
		{
			_IsMarquee = value;
			Marquee();
		}
	}


	public void Marquee()
	{
		if (IsMarquee)
		{
			timer.Start();
		}
		else
		{
			timer.Stop();
			textPoint = new PointF(0, 0);
			try
			{
				if (!IsDisposed)
				{
					Graphics g = CreateGraphics();
					g.Clear(BackColor);
					g.DrawString(Text, Font, new SolidBrush(ForeColor), textPoint);
				}
			}
		}
	}
}

代码:

/**
 * 跑马灯效果
 * @arrange (三零.脚本) www.q3060.com
 **/
private void button1_Click(object sender, EventArgs e)
{
	customLable1.IsMarquee = !customLable1.IsMarquee;
}

总结:

由于我们直接是在IsMarquee的set属性中就调用了Timer事件;所以即便不运行,在设计窗体时改变属性就可以直接看到效果。

效果:

C# 跑马灯效果的实现方法

 

您可能感兴趣的文章