2017-12-12 11 views
0

テキストを画面にゆっくりと書き込もうとしています。スペースバーを押したままにすると、テキストがより速く表示されます。それが再びリリースされると、同じ速度に戻ります。別のスレッドせずにこれを行う非同期タスクを使用してオンザフライでデータを変更するにはどうすればよいですか?

//Displays text at a certain speed 
public async void DisplayText(string text, Speed speed = Speed.medium, ConsoleColor color = ConsoleColor.White, bool newLine = false) 
{ 
    completed = false; 

    //Defines color and speed 
    Console.ForegroundColor = color; 
    scrollSpeed = DefineSpeed(speed); 

    var keyCheck = Task.Run(() => CheckSpeedUp()); 

    foreach (char c in text) 
    { 
     //If the asynchronous background method has detected the spacebar is pressed... 
     //Speed the text up, otherwise put it back to default. 
     if (speedUp) 
      scrollSpeed = 15; 
     else 
      scrollSpeed = 200; 

     Console.Write(c); 
     System.Threading.Thread.Sleep(scrollSpeed); 
    } 

    //Display has finished 
    completed = true; 

    //If there is a new line, write it 
    if (newLine) 
     Console.WriteLine(); 

    //Set the text color back to white 
    Console.ForegroundColor = ConsoleColor.White; 
} 

は、それが遅くなるだろうというとき、テキストがスピードアップ開始となりときの間の遅延の多くが生じました。 私はこれを、自分のスレッドで処理するタスクを作成することで解決しようとしました。そうすれば、メインコードはブーリアン「speedUp」について心配するだけです。

//Asynchronous task to check if the spacebar is pressed and set the speedUp bool 
private async Task CheckSpeedUp() 
{ 
    while(!completed) 
    { 
     if (Program.IsKeyDown(ConsoleKey.Spacebar)) 
     { 
      speedUp = true; 
     } 
     else 
     { 
      speedUp = false; 
     } 
    } 
} 

私は、このシステムは、foreachループはそのテキストを表示する速度をスピードアップし、スペースキーが解放されたときに再びそれを遅らせるだろうと思いました。

しかし、スペースバーが押された(またはタップされていても)約500ミリ秒後に、テキストはコードが変更されずに終了するまでスピードアップします。

答えて

0

ボタンbutton1とタイマtimer1を使ってwinformsアプリに何かをすばやくまとめると、これはうまくいくようです。私はフォームのKeyPreviewプロパティをtrueに設定しなければなりませんでした。

public partial class Form1 : Form 
{ 
    int _position = 0; 
    string _text = string.Empty; 

    private void button1_Click(object sender, EventArgs e) 
    { 
     if (!timer1.Enabled) 
      DisplayText(@"//Displays text at a certain speed test..."); 
    } 

    //Displays text at a certain speed 
    public void DisplayText(string text, int speed = 200, Color color = default(Color), bool newLine = false) 
    { 
     _position = 0; 
     _text = text; 
     timer1.Interval = speed; 

     timer1.Enabled = true; 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (_position < _text.Length) 
      Debug.Write(_text[_position]); 
     else 
      timer1.Enabled = false; 
     _position++; 
    } 

    private void Form1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Space) 
      timer1.Interval = 15; 
    } 

    private void Form1_KeyUp(object sender, KeyEventArgs e) 
    { 
     timer1.Interval = 200; 
    } 
} 

私はこれがあなたがやっていたことと少し違っていることを知っていますが、あなたは要点を得ることができますことを願っています。明瞭にするために、テキストの書き換え(テキストの色の変更など)に関係しないコードをすべて削除しました。

関連する問題