我有一个项目,在这里,它已默认设置的动作发生由MouseEnter事件。我的意思是,打开一个窗口,关闭,返回,一切,只发生了MouseEnter事件。
I have a project here and it has set by default that the actions occur by MouseEnter event. I mean, opening a Window, closing, returning, whatever, happens only by the MouseEnter event.
我被要求只有3秒后,使该事件火灾。这意味着,用户将将鼠标上的控制,仅在3秒后的事件必须发生在窗口中的所有控制。
I was requested to make the event fire only after 3 seconds. That means that the user will place the mouse on the control and only after 3 seconds the event must happen for all the controls in the window.
于是,我想到了一个全球性的定时器或相似的东西,这将返回false,直到计时器达到3 ...我认为,就是这样......
So, I thought about a global timer or something alike, that will return false untill the timer reaches 3... I think that's the way...
吉兹,没有任何人知道我怎么能做出这样的事?
Geez, does anybody knows how can I make such thing?
谢谢!
您可以定义一个类,将暴露一个 DelayedExecute
方法接收执行操作,并创建定时器根据需要,用于将延迟执行。它看起来是这样的:
You can define a class that will expose a DelayedExecute
method that receives an action to execute and creates timers as needed for the delayed execution. It would look something like this:
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();
}
}
然后,你可以这样调用它:
Then you can call it like this:
DelayedExecutionService.DelayedExecute(() => MessageBox.Show("Hello!"));
或
DelayedExecutionService.DelayedExecute(() =>
{
DoSomething();
DoSomethingElse();
});