用于触发事件WPF的计时器

Arm*_*ire 3 .net c# wpf events timer

我在这里有一个项目,它默认设置了MouseEnter事件发生的动作.我的意思是,打开一个Window,关闭,返回等等,只发生在MouseEnter事件中.

我被要求在3秒后使事件发生火灾.这意味着用户将鼠标放在控件上,并且仅在3秒后,窗口中的所有控件都必须发生事件.

所以,我想到了一个全球计时器或类似的东西,它将返回假,直到计时器达到3 ......我认为这就是......

Geez,有谁知道我怎么能做这样的事情?

谢谢!!

Adi*_*ter 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用它:

DelayedExecutionService.DelayedExecute(() => MessageBox.Show("Hello!"));
Run Code Online (Sandbox Code Playgroud)

要么

DelayedExecutionService.DelayedExecute(() => 
{
    DoSomething();
    DoSomethingElse();
});
Run Code Online (Sandbox Code Playgroud)