在间隔过去后,对MessageBox执行默认操作

时间:2022-03-08 15:51:42

Let's say I have a custom message box used as follows

假设我有一个自定义消息框,如下所示

MyWindow.ShowDialog();

I need to Close(), Hide() or execute a handler say Close_Click after say 1 second if no user action occurs.

我需要关闭(),隐藏()或执行处理程序,如果没有用户操作发生,请说1秒后关闭。

Thread.Sleep() and Timer approaches didn't help much.

Thread.Sleep()和Timer方法没有多大帮助。

EDIT:

编辑:

I did this in the window constructor

我在窗口构造函数中执行了此操作

    var timer = new System.Timers.Timer(timeOut);
    timer.Start();
    timer.Elapsed += (sender, e) =>
    {
      cmdClose_Click(null, null); //Attached to a button which normally does the job of closing the window.
    };

3 个解决方案

#1


3  

If you are using WPF, using a DispatcherTimer (System.Windows.Threading) on your custom message box will work. Just use the Tick event to call Close().

如果您使用的是WPF,则在自定义消息框中使用DispatcherTimer(System.Windows.Threading)将起作用。只需使用Tick事件来调用Close()。

#2


1  

I've had to do something similar in the past. What I did was initialise a System.Threading.Timer that ticks periodically. On each tick if I can close the window (because some background operation has completed) I set the DialogResult and call Close (making sure to check InvokeRequired).

我过去不得不做类似的事情。我所做的是初始化一个定期打勾的System.Threading.Timer。如果我可以关闭窗口(因为某些后台操作已完成),我会在每个刻度上设置DialogResult并调用Close(确保检查InvokeRequired)。

#3


1  

One second sounds too short to me, but anyway.

一秒钟对我来说听起来太短了,但无论如何。

Just add a Timer control to your custom message box form, enable it and set its Intervall to 1000. Then add a event for it's timer event and put the call to Close() inside.

只需将Timer控件添加到自定义消息框表单中,启用它并将其Intervall设置为1000.然后为其计时器事件添加一个事件,并将调用放入Close()。

#1


3  

If you are using WPF, using a DispatcherTimer (System.Windows.Threading) on your custom message box will work. Just use the Tick event to call Close().

如果您使用的是WPF,则在自定义消息框中使用DispatcherTimer(System.Windows.Threading)将起作用。只需使用Tick事件来调用Close()。

#2


1  

I've had to do something similar in the past. What I did was initialise a System.Threading.Timer that ticks periodically. On each tick if I can close the window (because some background operation has completed) I set the DialogResult and call Close (making sure to check InvokeRequired).

我过去不得不做类似的事情。我所做的是初始化一个定期打勾的System.Threading.Timer。如果我可以关闭窗口(因为某些后台操作已完成),我会在每个刻度上设置DialogResult并调用Close(确保检查InvokeRequired)。

#3


1  

One second sounds too short to me, but anyway.

一秒钟对我来说听起来太短了,但无论如何。

Just add a Timer control to your custom message box form, enable it and set its Intervall to 1000. Then add a event for it's timer event and put the call to Close() inside.

只需将Timer控件添加到自定义消息框表单中,启用它并将其Intervall设置为1000.然后为其计时器事件添加一个事件,并将调用放入Close()。