2012-10-09 22 views
5

例えば、MP3リーダーの前進ボタンのように、長時間に亘ってButtonが押されたときに、アクションを繰り返したいと思います。 WinFormに既存のC#イベントがありますか?長押しボタン

私はアクションを実行し、MouseUpイベントでそれを停止しますタイマーを起動するMouseDownイベントを処理することができますが、私はこの問題=>つまり解決する簡単な方法を探しています:Timerない溶液(またはスレッド/ 仕事 ...)。

答えて

0

MouseDownとMouseUpの間でtimerを使用できます。

MouseDownEvent 

Timer tm1; 

MouseUpEvent 

Timer tm2; 

2つのタイマーの間で簡単に処理できます。

0

MP3トラックで数秒間スキップするなど、ボタンを押している間に何らかのアクションを実行する必要があります。

mouseUpでキャンセルされるタイマーを起動すると、ボタンが押されている間に一定の間隔(100ms?)でその種の作業がトリガーされます。簡単に実装でき、UIではブロックされません。

より簡単な解決策は、おそらくUIをブロックさせるでしょう。

4

更新日:最短の方法:

Anonymous MethodsObject Initializerの使用:

public void Repeater(Button btn, int interval) 
{ 
    var timer = new Timer {Interval = interval}; 
    timer.Tick += (sender, e) => DoProgress(); 
    btn.MouseDown += (sender, e) => timer.Start(); 
    btn.MouseUp += (sender, e) => timer.Stop(); 
    btn.Disposed += (sender, e) => 
         { 
          timer.Stop(); 
          timer.Dispose(); 
         }; 
} 
+0

MouseUpでもTickイベントの登録を解除する方がよい。 –

+0

また、タイマーを処分することを忘れないでください。 – Joe

+0

あなたは 'Timer'を使っていますが、匿名メソッドは実際のメソッドを書き込むのではなく、最短の方法です。これはFramework 4.0には存在しませんか? –

0

私は、アクションを実行し、MouseUpイベントでそれを停止しますタイマーを起動するためにMouseDownイベントを処理することができますが、私はこの問題を解決する簡単な方法を探しています

再利用可能な方法で一度書き込むと簡単にできます。この動作を持つ独自のButtonクラスを派生させることができます。

または、この動作にするために任意のボタンにアタッチできるクラスを作成します。次のようにあなたがそれを使用することになり

class ButtonClickRepeater 
{ 
    public event EventHandler Click; 

    private Button button; 
    private Timer timer; 

    public ButtonClickRepeater(Button button, int interval) 
    { 
     if (button == null) throw new ArgumentNullException(); 

     this.button = button; 
     button.MouseDown += new MouseEventHandler(button_MouseDown); 
     button.MouseUp += new MouseEventHandler(button_MouseUp); 
     button.Disposed += new EventHandler(button_Disposed); 

     timer = new Timer(); 
     timer.Interval = interval; 
     timer.Tick += new EventHandler(timer_Tick); 
    } 

    void button_MouseDown(object sender, MouseEventArgs e) 
    { 
     OnClick(EventArgs.Empty); 
     timer.Start(); 
    } 

    void button_MouseUp(object sender, MouseEventArgs e) 
    { 
     timer.Stop(); 
    } 

    void button_Disposed(object sender, EventArgs e) 
    { 
     timer.Stop(); 
     timer.Dispose(); 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     OnClick(EventArgs.Empty); 
    } 

    protected void OnClick(EventArgs e) 
    { 
     if (Click != null) Click(button, e); 
    } 
} 

簡潔
private void Form1_Load(object sender, EventArgs e) 
{ 
    ButtonClickRepeater repeater = new ButtonClickRepeater(this.myButton, 1000); 
    repeater.Click += new EventHandler(repeater_Click); 
} 

以上、あなたはButtonClickRepeaterへの参照を保持する必要がないので:

をたとえば次のような何かを行うことができます
private void Form1_Load(object sender, EventArgs e) 
{ 
    new ButtonClickRepeater(this.myBbutton, 1000).Click += new EventHandler(repeater_Click); 
} 
関連する問題