3

ここにプロジェクトがあり、デフォルトでは、アクションはMouseEnterイベントによって発生するように設定されています。つまり、ウィンドウを開いたり、閉じたり、戻ったりすることは、MouseEnterイベントによってのみ発生します。

3秒後にイベントを発生させるように要求されました。つまり、ユーザーはマウスをコントロールに置き、3秒後にのみ、ウィンドウ内のすべてのコントロールに対してイベントが発生する必要があります。

だから、私はグローバルタイマーか何かについて考えました、それはタイマーが3に達するまでfalseを返します...私はそれが方法だと思います...

ねえ、誰かが私がそのようなものを作ることができる方法を知っていますか?

ありがとう!!

4

2 に答える 2

7

DelayedExecute実行するアクションを受け取り、遅延実行の必要に応じてタイマーを作成するメソッドを公開するクラスを定義できます。次のようになります。

public static class DelayedExecutionService
{
    // We keep a static list of timers because if we only declare the timers
    // in the scope of the method, they might be garbage collected prematurely.
    private static IList<DispatcherTimer> timers = new List<DispatcherTimer>();

    public static void DelayedExecute(Action action, int delay = 3)
    {
        var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();

        // Add the timer to the list to avoid it being garbage collected
        // after we exit the scope of the method.
        timers.Add(dispatcherTimer);

        EventHandler handler = null;
        handler = (sender, e) =>
        {
            // Stop the timer so it won't keep executing every X seconds
            // and also avoid keeping the handler in memory.
            dispatcherTimer.Tick -= handler;
            dispatcherTimer.Stop();

            // The timer is no longer used and shouldn't be kept in memory.
            timers.Remove(dispatcherTimer);

            // Perform the action.
            action();
        };

        dispatcherTimer.Tick += handler;
        dispatcherTimer.Interval = TimeSpan.FromSeconds(delay);
        dispatcherTimer.Start();
    }
}

次に、次のように呼び出すことができます。

DelayedExecutionService.DelayedExecute(() => MessageBox.Show("Hello!"));

また

DelayedExecutionService.DelayedExecute(() => 
{
    DoSomething();
    DoSomethingElse();
});
于 2012-09-09T19:24:37.573 に答える
1

もっと簡単なソリューションを追加したかっただけです:

public static void DelayedExecute(Action action, int delay = 3000)
{
    Task.Factory.StartNew(() => 
    {
        Thread.Sleep(delay);
        action();
    }
}

次に、この他の回答と同じように使用します

于 2012-09-15T15:26:51.617 に答える