winforms 如何逐个显示每个字符并将其显示为标签

gdrx4gfi  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(104)

我试着将char转换为ToString(),但它只显示了句子的最后一个字符,即管理员的“N”。基本上,我想通过显示线程中的每个字符来显示整个句子。

public partial class Form1 : Form
    {
        string quote;
        public Form1()
        {
            InitializeComponent();

           quote = "Tips: Sometimes just leave her, to pause. - Admin";
            for (int i=0; i < quote.Length; i++){

               label1.Text =quote[i].ToString();
                Thread.Sleep(100);
            }
        }
    }
}

输出如下:enter image description here我也增加了标签的长度:enter image description here这才是我真正想要的,伙计们:enter image description here

7z5jn7bk

7z5jn7bk1#

正如所述,您应该使用winforms Timer每100 ms更新一次UI线程:

private void Form1_Load(object sender, EventArgs e)
{
    System.Windows.Forms.Timer updateLabelTimer = new();
    string quote = "Tips: Sometimes just leave her, to pause. - Admin";        
    int currentIndex = 0;

    updateLabelTimer.Tick += new EventHandler(UpdateLabelHandler);
    updateLabelTimer.Interval = 100;
    updateLabelTimer.Start();

    void UpdateLabelHandler(object? timerSender, EventArgs args)
    {
        label1.Text += quote[currentIndex];
        if (++currentIndex == quote.Length)
        {
            updateLabelTimer.Enabled = false;
        }
    }
}

相关问题