How to implement the same effect of marquees in winform?

旧时模样 提交于 2019-12-11 07:45:18

问题


I would like to make the text scrolling upwards or downloads.

In html we can use Marquees "Cool Effects with Marquees!" , sample2 The c# WebBrowser control doesn't recognize the syntax of Marquees

One way in c# is to use listbox, then rolling the listbox using timer.

I am wondering if there is an easy way to do it.


回答1:


If you want to draw animated text on a control, you need to create a custom control, having a timer, then move the text location in the timer and invalidate the control. Override its paint and render the text in new location.

You can find a Left to Right and Right to Left Marquee Label in my other answer here: Right to Left and Left to Right Marquee Label in Windows Forms.

Example - Top to Bottom Marquee Label in Windows Forms

In the following example, I've created a MarqueeLabel control which animates the text vertically:

using System;
using System.Drawing;
using System.Windows.Forms;
public class MarqueeLabel : Label
{
    Timer timer;
    public MarqueeLabel()
    {
        DoubleBuffered = true;
        timer = new Timer();
        timer.Interval = 100;
        timer.Enabled = true;
        timer.Tick += Timer_Tick;
    }
    int? top;
    int textHeight = 0;
    private void Timer_Tick(object sender, EventArgs e)
    {
        top -= 3;
        if (top < -textHeight)
            top = Height;
        Invalidate();
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        e.Graphics.Clear(BackColor);
        var s = TextRenderer.MeasureText(Text, Font, new Size(Width, 0),
            TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak);
        textHeight = s.Height;
        if (!top.HasValue) top = Height;
        TextRenderer.DrawText(e.Graphics, Text, Font,
            new Rectangle(0, top.Value, Width, textHeight),
            ForeColor, BackColor, TextFormatFlags.TextBoxControl |
            TextFormatFlags.WordBreak);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
            timer.Dispose();
        base.Dispose(disposing);
    }
}


来源:https://stackoverflow.com/questions/54271604/how-to-implement-the-same-effect-of-marquees-in-winform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!