使用 for 语句更新标签(打字机效果)
Updating a label using a for statement (typewriter effect)
我正在 Windows Forms (.NET-framework) 中开发游戏,我想为我显示的文本添加打字机效果(以便它显示逐个字母)。我为此使用了一个for循环。文本显示在标签中。
我有 2 个变量。 1个保存所有文本,一个保存需要在循环中打印出来的文本:
public string FullText;
private string CurrentText = "";
我想用循环更新的标签叫做:LblTextBottom
这是我单击相应按钮时执行的方法:
public void TypeWriterEffect()
{
for(int i=0; i < FullText.Length; i++)
{
CurrentText = FullText.Substring(0, i);
LblTextBottom.Text = CurrentText;
Thread.Sleep(10);
}
}
这是当我点击 运行 TypeWriterEffect 方法的按钮时激活的代码:
private void Button1_Click(object sender, EventArgs e)
{
FullText = LblTextBottom.Text;
ShowText();
}
它更新了 Label,并且代码有效,但我没有看到它实时更新(文本没有一个字母一个字母地显示)。我试过使用单独的线程来更新控件,但我没有让它工作。
当然,如果此代码有效,我就不会在这里。但是不知道为什么不更新。所以任何帮助将不胜感激:)
P.s: This is what I'm looking for,但当然没有 UnityEngine 类 和命名空间(不能使用那些)。
编辑: 忘了告诉您,单击按钮时,新的文本字符串会从不同的 .cs 文件加载到 LblTextBottom
。
如果你写得一般,那么你可以让多台打字机同时打字:
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
await TypeWriterEffect("This is some text to be `typed`...", LblTextBottom, 100);
button1.Enabled = true;
}
private async void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
await TypeWriterEffect("Look mom, we're running at the same time!!!", label2, 200);
button2.Enabled = true;
}
public Task TypeWriterEffect(string txt, Label lbl, int delay)
{
return Task.Run(() =>
{
for (int i = 0; i <= txt.Length; i++)
{
lbl.Invoke((MethodInvoker)delegate {
lbl.Text = txt.Substring(0, i);
});
System.Threading.Thread.Sleep(delay); ;
}
});
}
制作中:
我正在 Windows Forms (.NET-framework) 中开发游戏,我想为我显示的文本添加打字机效果(以便它显示逐个字母)。我为此使用了一个for循环。文本显示在标签中。
我有 2 个变量。 1个保存所有文本,一个保存需要在循环中打印出来的文本:
public string FullText;
private string CurrentText = "";
我想用循环更新的标签叫做:LblTextBottom
这是我单击相应按钮时执行的方法:
public void TypeWriterEffect()
{
for(int i=0; i < FullText.Length; i++)
{
CurrentText = FullText.Substring(0, i);
LblTextBottom.Text = CurrentText;
Thread.Sleep(10);
}
}
这是当我点击 运行 TypeWriterEffect 方法的按钮时激活的代码:
private void Button1_Click(object sender, EventArgs e)
{
FullText = LblTextBottom.Text;
ShowText();
}
它更新了 Label,并且代码有效,但我没有看到它实时更新(文本没有一个字母一个字母地显示)。我试过使用单独的线程来更新控件,但我没有让它工作。
当然,如果此代码有效,我就不会在这里。但是不知道为什么不更新。所以任何帮助将不胜感激:)
P.s: This is what I'm looking for,但当然没有 UnityEngine 类 和命名空间(不能使用那些)。
编辑: 忘了告诉您,单击按钮时,新的文本字符串会从不同的 .cs 文件加载到 LblTextBottom
。
如果你写得一般,那么你可以让多台打字机同时打字:
private async void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
await TypeWriterEffect("This is some text to be `typed`...", LblTextBottom, 100);
button1.Enabled = true;
}
private async void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
await TypeWriterEffect("Look mom, we're running at the same time!!!", label2, 200);
button2.Enabled = true;
}
public Task TypeWriterEffect(string txt, Label lbl, int delay)
{
return Task.Run(() =>
{
for (int i = 0; i <= txt.Length; i++)
{
lbl.Invoke((MethodInvoker)delegate {
lbl.Text = txt.Substring(0, i);
});
System.Threading.Thread.Sleep(delay); ;
}
});
}
制作中: