2017-09-10 19 views
-1

我想將文本插入標籤,但文本必須慢慢插入/按字母/字母/字母, 有點像在舊的MUD遊戲中。獲取標籤以緩慢插入文本

到目前爲止,我已經試着這樣做:

private void StoryBox_Click(object sender, EventArgs e) 
{ 
    string text = StoryBox.Text; 
    var index = 0; 
    var timer = new System.Timers.Timer(2000); 

    timer.Elapsed += delegate 
    { 
     if (index < text.Length) 
     { 
      index++; 
      StoryBox.Text = "This should come out pretty slowly "; 
     } 
     else 
     { 
      timer.Enabled = false; 
      timer.Dispose(); 
     } 
    }; 

    timer.Enabled = true; 
} 

這是我從網站上收集的,但我不是特別明白爲什麼這是行不通的。

正如你可以看到它在StoryBox_Click下。
有沒有辦法讓這個自動化?所以當程序打開時,它會計算幾秒鐘,然後開始寫出文本。

+0

你是什麼意思?你的意思是寫信嗎? – Youssef13

+0

@ Youssef13是的。 –

回答

0

試試這個:

private async void button1_Click(object sender, EventArgs e) 
{ 
    string yourText = "This should come out pretty slowly"; 
    label1.Text = string.Empty; 
    int i = 0; 
    for (i = 0; i <= yourText.Length - 1; i++) 
    { 
     label1.Text += yourText[i]; 
     await Task.Delay(500); 
    } 
} 
0

您可以使用YourFormShown - 活動時,你希望你的圖形用戶界面打開後啓動它。

所以重用您提供的代碼,並改變了一些東西,這可能爲你工作:

添加私有字段YourForm類:

private Timer _timer; 
private int _index; 
private string _storyText; 

YourForm構造函數初始化它

public YourForm() 
{ 
    InitializeComponent(); 

    // init private fields; 
    this._index = 0; 
    this._storyText = "This should come out pretty slowly"; 

    // Timer Interval is set to 1 second 
    this._timer = new Timer { Interval = 1000 }; 

    // Adding EventHandler to Shown Event 
    this.Shown += this.YourForm_Shown; 

    this._timer.Tick += delegate 
    { 
     if (this._index < this._storyText.Length) 
     { 
      StoryBox.Text += this._storyText[this._index]; 
      this._index++; 
     } 
     else 
     { 
      this._timer.Stop(); 
     } 
    }; 
} 

Shown事件爲YourForm

private void YourForm_Shown(object sender, EventArgs e) 
{ 
    this._timer.Start(); 
}