日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C#實現(xiàn)跑馬燈效果的示例代碼_C#教程

作者:Csharp小記 ? 更新時間: 2022-12-06 編程語言

文章描述

跑馬燈效果,功能效果大家應(yīng)該都知道,就是當(dāng)我們的文字過長,整個頁面放不下的時候(一般用于公告等),可以讓它自動實現(xiàn)來回滾動,以讓客戶可以看到完整的信息(雖然要多等一會兒時間)。

其實對于Winform這種技術(shù),實現(xiàn)任何的動態(tài)效果相對來說都比較麻煩。而且一般都需要搭配定時器使用,當(dāng)然,這次要寫的跑馬燈效果也是一樣的,使用了System.Timers.Timer來實現(xiàn),關(guān)于其他定時器以及用法,之前文章有寫過,有興趣的可以翻一下。

因為使用麻煩,所以要進(jìn)行封裝,所以要不斷的造輪子(盡管是重復(fù)的),但重復(fù)也是一個加強(qiáng)記憶以及不斷深入的過程,我認(rèn)為這并不是多余的。因此,為了方便調(diào)用,還是用自定義控件封裝一下屬性,使用的時候只要設(shè)置屬性即可。

開發(fā)環(huán)境

.NET Framework版本:4.5

開發(fā)工具

?Visual Studio 2013

實現(xiàn)代碼

 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;
        }

實現(xiàn)效果

代碼解析:由于我們直接是在IsMarquee的set屬性中就調(diào)用了Timer事件;所以即便不運(yùn)行,在設(shè)計窗體時改變屬性就可以直接看到效果。

原文鏈接:https://mp.weixin.qq.com/s/WOQs_XvDD8Hq9aM-_ERDYw

欄目分類
最近更新