public partial class HorseRaceLamp : UserControl
{
PointF pf;
Font f = new Font("微软雅黑", 10);
Color c = Color.White;
string temp;
int i = 0;
System.Timers.Timer HelpTime;
Bitmap bmp = null;
Graphics g = null;
List<string> pmdList { get; set; }
public HorseRaceLamp()
{
InitializeComponent();
this.Visible = false;
}
Object obj = new object();
/// <summary>
/// 启动跑马灯
/// </summary>
public void StartPMD(List<string> stringList)
{
try
{
if (stringList.Any())
{
bmp = new Bitmap(this.pictureBox_pmd.Width, this.pictureBox_pmd.Height);
g = Graphics.FromImage(bmp);
lock (obj)
{
this.Visible = true;
pmdList = stringList;
this.pictureBox_pmd.Text = pmdList[i];
c = pictureBox_pmd.BackColor;
HelpTime = new System.Timers.Timer();//实例化一个时间控件
HelpTime.Enabled = true;//让时间控件可用
HelpTime.Interval = 100;//时间间隔100毫秒
HelpTime.Elapsed += new System.Timers.ElapsedEventHandler(HelpTime_Tick); ;//注册时间控件的Tick事件
HelpTime.Start();
pf = new PointF(this.pictureBox_pmd.Size.Width, 0);
}
}
}
catch (Exception ex)
{
LogManageBusiness.WriteLog(ex, this.GetType().FullName, "StartPMD");
}
}
private void HelpTime_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
while (!this.IsHandleCreated)//等待句柄
{ }
if (this.IsHandleCreated)
{
this.Invoke(new Action(() =>
{
SizeF s = new SizeF();
s = g.MeasureString(pmdList[i], f);//测量文字长度
Brush brush = Brushes.Red;
g.Clear(c);//清除背景
if (temp != pmdList[i])//文字改变时,重新显示
{
pf = new PointF(this.pictureBox_pmd.Size.Width, 0);
temp = pmdList[i];
}
else
{
pf = new PointF(pf.X - 1, 0);//每次偏移1
}
if (pf.X <= -s.Width)
{
pf = new PointF(this.pictureBox_pmd.Size.Width, 0);
if (i == pmdList.Count - 1)
{
i = 0;
}
else
{
i++;
}
}
g.DrawString(pmdList[i], f, brush, pf);
pictureBox_pmd.Image = bmp;
}));
}
}
catch
{
HelpTime.Stop();
HelpTime.Enabled = false;
}
}
}
实现跑马灯效果的原理启动一个定时器,注册一个事件,让定时器不停的跑。需要用到Graphics这绘图的类,每次在控件上绘制文字,计算文字长度与偏移量来实现跑马灯的效果
winfrom lable控件实现跑马灯效果
最新推荐文章于 2022-11-15 07:49:03 发布