2012-02-23 3 views
1

ステータスバーのラベルがあり、ステータスバーのラベルに3秒間テキストを表示したい特定の時間(3秒など)のラベルにテキストを表示するにはどうすればよいですか?

スレッドを使用せずにどうすればいいですか?

public void InfoLabel(string value) 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new Action<string>(InfoLabel), new object[] { value }); 
      return; 
     } 
     infoLabel.Text = value; 
    } 
+0

は、WPFのために、このですかASP.NETでHTMLにラベルにそれを言うのですか? – likestoski

答えて

6

単にあなたの方法の終わりにタイマーを追加します。

if (!string.IsNullOrWhiteSpace(value)) 
{ 
    System.Timers.Timer timer = new System.Timers.Timer(3000) { Enabled = true }; 
    timer.Elapsed += (sender, args) => 
    { 
     this.InfoLabel(string.Empty); 
     timer.Dispose(); 
    }; 
} 
+0

感謝の男..敬意 –

0

あなたは常に少なくともGUIスレッドを使用しています。そのスレッドを待つことにした場合、他のコントロールとのやりとりはできません(つまり、ボタンは機能しません。ウィンドウは再描画されません)。

また、OSやその他のタイプのタイマーに制御を戻すSystem.Windows.Forms.Timerを使用することもできます。いずれにしても、「カウントダウン」はユーザーのやりとりをブロックするか、別のスレッド(フードの下)で発生します。

1

Elapsedイベントを発生させるまでにn秒間待機するタイマーのインスタンスを作成するには、Timerを使用します。経過イベントでは、ラベルのContentをクリアします。

タイマーは別のスレッドで実行されるため、タイマーがカウントされている間はUIスレッドはロックされず、UIで他の操作を自由に実行できます。

private delegate void NoArgDelegate(); 

private void StartTimer(int durationInSeconds) 
{ 
    const int milliSecondsPerSecond = 1000; 
    var timer = new Timer(durationInSeconds * milliSecondsPerSecond); 
    timer.Start(); 
    timer.Elapsed += timer_Elapsed; 
} 

private void timer_Elapsed(object sender, ElapsedEventArgs e) 
{ 
    var clearLabelTextDelegate = new NoArgDelegate(ClearLabelText); 
    this.Dispatcher.BeginInvoke(clearLabelTextDelegate); 
} 

private void ClearLabelText() 
{ 
    this.myLabel.Content = string.Empty; 
} 

私はあなたのコードの残りの部分をしない限り、いくつかの提案は、タイマーを起動し、複数のUIイベントを防止するようにタイマーのロックを作成することです。さらに、デリゲートとタイマーインスタンスは、クラスのメンバーとしてprivateとして作成できます。

3

あなたはあなたがあなたのテキストを表示する必要があるたびに呼び出す関数を定義する必要があり、この関数内で使用すると、タイマーを定義し、このタイマーがありますSystem.Windows.Forms.Timerに基づいて、唯一の違いは、実行時間を表すstopTimeパラメータを保持するように変更されていることです。唯一必要なことは、開始コード(表示テキスト)をMyFunction関数内に置き、終了コードTimer_Tickファンクションの中でテキストの表示を停止するには、MyFunctionと呼ぶと、その中で実行する秒数を指定するだけです関数のパラメータです。

private void MyFunction(int durationInSeconds) 
    { 
     MyTimer timer = new MyTimer(); 
     timer.Tick += new EventHandler(Timer_Tick); 
     timer.Interval = (1000) * (1); // Timer will tick every second, you can change it if you want 
     timer.Enabled = true; 
     timer.stopTime = System.DateTime.Now.AddSeconds(durationInSeconds); 
     timer.Start(); 
     //put your starting code here 
    } 

    private void Timer_Tick(object sender, EventArgs e) 
    { 
     MyTimer timer = (MyTimer)sender; 
     if (System.DateTime.Now >= timer.stopTime) 
     { 
      timer.Stop(); 
      //put your ending code here 
     } 
    } 

修正Timerクラス

public class MyTimer : System.Windows.Forms.Timer 
{ 
    public System.DateTime stopTime; 
    public MyTimer() 
    { 

    } 
} 
関連する問題