目录
文章描述
跑马灯效果,功能效果大家应该都知道,就是当我们的文字过长,整个页面放不下的时候(一般用于公告等),可以让它自动实现来回滚动,以让客户可以看到完整的信息(虽然要多等一会儿时间)。
其实对于Winform这种技术,实现任何的动态效果相对来说都比较麻烦。而且一般都需要搭配定时器使用,当然,这次要写的跑马灯效果也是一样的,使用了System.Timers.Timer来实现,关于其他定时器以及用法,之前文章有写过,有兴趣的可以翻一下。
因为使用麻烦,所以要进行封装,所以要不断的造轮子(尽管是重复的),但重复也是一个加强记忆以及不断深入的过程,我认为这并不是多余的。因此,为了方便调用,还是用自定义控件封装一下属性,使用的时候只要设置属性即可。
开发环境
.NET Framework版本:4.5
开发工具
Visual Studio 2013
实现代码
- 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);
- }
- }
- }
- }
- }
复制代码- private void button1_Click(object sender, EventArgs e)
- {
- customLable1.IsMarquee = !customLable1.IsMarquee;
- }
复制代码 实现效果
代码解析:由于我们直接是在IsMarquee的set属性中就调用了Timer事件;所以即便不运行,在设计窗体时改变属性就可以直接看到效果。
到此这篇关于C#实现跑马灯效果的示例代码的文章就介绍到这了,更多相关C#跑马灯内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟! |