如何将标签的文字从右向左移动,当一个角色隐藏在左边时,它会显示在右边?

时间:2016-04-03 19:53:34

标签: c# label controls

这是我的密码:

using System;
using System.Windows.Forms;
namespace Scroller
{
    public partial class Form1 : Form
    {
        int i, j;
        bool k = false;
        public Form1()
        {
            InitializeComponent();                                  
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text = "Time:"+ System.DateTime.Now.ToString();
            i--;
            j = i + this.Width;
            if (i < this.Width && i > 0)
            {
                label1.Left = i;
            }
            else
            if (i < 0 && k == false)
            {
                label1.Left = i;
                k = true;
            }
            else
            if (i < 0 && k == true)
            {
                label1.Left = j;
                k = false;
            }

            if (i < 0 - label1.Width)
            {
                i = this.Width - label1.Width;
            }
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Time:"+  System.DateTime.Now.ToString();
            i = this.Width - label1.Width;
            label1.Left = i;
        }
    }
}

我想要的效果是整个时间字符串从右向左移动。当文本的像素在左侧消失时(因为它不在形式的左边框内),像素将显示在右侧。

换句话说,可以通过删除字符串的第一个字符并将其附加到最后一个字符来实现效果。

我知道使用两个标签会更容易。在表单中设置一个位置,并通过表单隐藏另一个位置。同时移动它们。

当第一个标签点击表单的左边框时,第二个标签会点击表单的右边框。并且第一个移出,第二个移动。直到第二个完全移入,重置他们的x位置。

但我只想使用一个标签。所以我选择快速切换标签的位置,并尝试&#34;欺骗&#34;用户的眼睛。 问题是当标签在左右之间切换时,它会非常明显地闪烁。即使我将计时器的间隔设置为低于20,问题仍然存在。

你能帮助我解决闪光问题,或者启发我可以使用一个标签和一个计时器以达到我需要的效果吗?

感谢。如果我没有描述我的问题,或者需要更多代码,请告诉我。

1 个答案:

答案 0 :(得分:0)

我认为你不能解决在Windows窗体中更改标签位置的闪烁问题。

另一种解决方案是将标签宽度设置为与表单宽度相同的大小,使标签文本使用空格填充所有宽度,并使计时器始终获取最后一个字符并将其放在字符串的开头。< / p>

以下示例代码。

private void timer1_Tick(object sender, EventArgs e)
{
    label1.Text = label1.Text.Substring(label1.Text.Length - 1) + label1.Text.Remove(label1.Text.Length - 1);
}

private void Form1_Load(object sender, EventArgs e)
{
    // The total spaces required to fill the form vary from form.width and the initial label.text.width
    // Width | Spaces
    //  177  |   13
    //  228  |   30
    //  297  |   53
    //  318  |   60

    // The spacesEnd = 60 work for a form with width 319
    int spacesBegin = 0, spacesEnd = 60;

    label1.Text = "Time:" + System.DateTime.Now.ToString();
    label1.AutoSize = false;
    label1.Left = -3;
    label1.Width = this.Width - 1;
    label1.Height = 15;
    label1.BorderStyle = BorderStyle.FixedSingle;

    for (int i = 0; i < spacesBegin; i++)
        label1.Text = " " + label1.Text;
    for (int i = 0; i < spacesEnd; i++)
        label1.Text += " ";

    Timer timer = new Timer();
    timer.Tick += timer1_Tick;
    timer.Interval = 50;
    timer.Start();
}