效果展示:
winfrom 文字跑马灯
这里HelpTime是Winfrom的定时器控件,HelpText是Winfrom的Lable控件
public partial class Form1 : Form
{
public string text = "这里要替换的文字";
PointF p;
Font f = new Font("宋体", 20);
//这里RGP值是改变背景,可以根据需要更改
Color c = Color.FromArgb(237, 232, 236);
string temp;
// 添加一个新的标志来检测鼠标是否在HelpText1上
bool isMouseOver = false;
public Form1()
{
InitializeComponent();
HelpTime.Enabled = true;//让时间控件可用
HelpTime.Interval = 150;//时间间隔150毫秒 速度控制
p = new PointF(this.HelpText1.Size.Width, 0);
}
private void Form1_Load(object sender, EventArgs e)
{//大小
this.HelpText1.Size=new Size(500, 30);
}
private void HelpTime_Tick(object sender, EventArgs e)
{
if (isMouseOver) {
return;
}
Graphics g = this.HelpText1.CreateGraphics();
SizeF s = new SizeF();
s = g.MeasureString(text, f);//测量文字长度
Brush brush = Brushes.Black;
g.Clear(c);//清除背景
if (temp != text)//文字改变时,重新显示
{
p = new PointF(this.HelpText1.Size.Width, 0);
temp = text;
}
else
p = new PointF(p.X - 10, 0);//每次偏移10
if (p.X <= -s.Width)
p = new PointF(this.HelpText1.Size.Width, 0);
g.DrawString(text, f, brush, p);
}
//这里实现了鼠标移上来滚动停止
private void HelpText1_MouseEnter(object sender, EventArgs e)
{
// 设置标志为true,表示鼠标移进了HelpText1
isMouseOver = true;
}
//这里实现了鼠标离开滚动继续
private void HelpText1_MouseLeave(object sender, EventArgs e)
{
// 设置标志为false,表示鼠标离开了HelpText1
isMouseOver = false;
}
}