我做聊天软件时很想做到跟 艾伦 · 走路人 的 MV 这样的逐字输出效果:
是我三年前太L了,明明非常简单但是偏要弄那么麻烦
现在的需求是点击按钮 button1 让 Label label1 逐字输出文字“Apart, but still together.”,先新建个 Timer timer1,然后代码如下
private void button1_Click(object sender, EventArgs e)
{
this.showText("Apart, but still together.");
}
String text = "";
int nowPosition = 0;
public void showText(string str)
{
this.label1.Text = "";
this.text = str;
this.nowPosition = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (nowPosition < text.Length)
{
label1.Text += text.ToCharArray()[nowPosition];
nowPosition++;
}
}
这么简单就能做到的事情,在三年前我竟然用下面这么长的代码?
旧代码:(不推荐使用)
当时不会弄,我就去百度知道提问。他说要用for和多线程。
然后我就慢慢地写了这代码:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
ListBox DelayShowText = new ListBox();
public Form1()
{
InitializeComponent();
DelayShowText.Visible = false;//不显示用于显示文字的控件
DelayShowText.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
Control.CheckForIllegalCrossThreadCalls = false;//不捕捉对错误线程的控件
}
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;//声明将要被分隔的文本
int a = s.Length;//声明引索
while (true)//循环
{
s = s.Insert(a, "≌");//从后面开始插入分隔符(以免bug,而且分隔符最好不怎么常见)
a--;//减少引索
if (a == 0)//如果插入分隔符完成
break;//跳出循环
}
string[] Stri = s.Split('≌');//将文本用写入组数(要输入上面的分隔符)
foreach(string str in Stri)//遍历组数
{
DelayShowText.Items.Add(str);//加入组数到列表框
}
DelayShowText.SelectedIndex = 0;//选择第一个项以开始输出
//richTextBox1.Text += textBox1.Text + "\n\r\n\r";//直接输出信息
}
/// <summary>
/// 文字显示的延迟(单位:毫秒)
/// </summary>
int delay = 20;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread t1 = new System.Threading.Thread(() =>//使用多线程(否则会卡住一会)
{
try//全程捕捉错误不提示,怕出bug
{
if (DelayShowText.SelectedIndex < DelayShowText.Items.Count)//如果没显示完成
{
System.Threading.Thread.Sleep(delay);//延迟
richTextBox1.Text += DelayShowText.SelectedItem.ToString();//追加文本
DelayShowText.SelectedIndex += 1;//下一个
}
}
catch//捕捉到错误就算是显示完成了……
{
DelayShowText.Items.Clear();//清空列表框
richTextBox1.Text += "\n\r\n\r";//换两行
}
}); t1.Start();//启动线程
}
}
}
已测试可用