Coo*_* Do 5 c# label timer winforms
我正在寻找一种像网络术语中的选取框一样滚动文本的有效方法。
我设法使用我在网上找到的一段代码来实现这一点:
private int xPos = 0, YPos = 0;
private void Form1_Load(object sender, EventArgs e)
{
//link label
lblText.Text = "Hello this is marquee text";
xPos = lblText.Location.X;
YPos = lblText.Location.Y;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (xPos == 0)
{
this.lblText.Location = new System.Drawing.Point(this.Width, YPos);
xPos = this.Width;
}
else
{
this.lblText.Location = new System.Drawing.Point(xPos, YPos);
xPos -= 2;
}
}
Run Code Online (Sandbox Code Playgroud)
代码非常简单,它使用了一个计时器滴答事件。
它最初运行良好,但在滚动 3 或 4 次后,它不再出现。
有什么我可以调整以使滚动无限的吗?
尝试:
private void timer1_Tick(object sender, EventArgs e)
{
if (xPos <= 0) xPos = this.Width;
this.lblText.Location = new System.Drawing.Point(xPos, YPos);
xPos -= 2;
}
Run Code Online (Sandbox Code Playgroud)
您提到如果字符串比表单宽度长,它就会“切断”。我假设您的意思是标签一碰到左侧就跳回到表单的右侧,这意味着您无法阅读全文?
如果是这样,您可以将标签的“最小左侧”设置为其宽度的负数。这将允许标签在重置之前完全滚动离开表单:
private void timer1_Tick(object sender, EventArgs e)
{
// Let the label scroll all the way off the form
int minLeft = this.lblText.Width * -1;
if (xPos <= minLeft) xPos = this.Width;
this.lblText.Location = new Point(xPos, yPos);
xPos -= 2;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将“最小左侧”设置为标签宽度和表单宽度之间的差值的负数,这样在显示最右边的字符之前它不会重置:
private void timer1_Tick(object sender, EventArgs e)
{
// Ensure that the label doesn't reset until you can read the whole thing:
int minLeft = (lblText.Width > this.Width) ? this.Width - lblText.Width : 0;
if (xPos <= minLeft) xPos = this.Width;
this.lblText.Location = new Point(xPos, yPos);
xPos -= 2;
}
Run Code Online (Sandbox Code Playgroud)
还有许多其他选择。就像有多个标签背靠背轮流运行一样,所以永远不会有任何空白文本!您可以计算出要动态生成多少个标签(根据它们的宽度和表单宽度之间的差异)并处理它们在计时器事件中的位置。
| 归档时间: |
|
| 查看次数: |
6769 次 |
| 最近记录: |