如何制作等待响应最多30秒的定时对话框?

时间:2012-12-11 11:12:18

标签: c# dialog

我试图在C#中绕过线程,但是我很难实现这种行为。

我需要一个简单的是/否对话框,在30秒后返回DialogResult.No

到目前为止我得到的是:

Thread th = new Thread(() =>
{
    try
    {
        result = message.ShowDialog();
    }
    catch (Exception)
    {

    }
});
th.Start();
Thread.Sleep(30000);
th.Abort();

当我在对话框中选择“是”或“否”时,它仍然等待30秒,我需要线程在收到响应时停止。

这可能不是一件容易的事,但我对C#比较陌生,可以在这方面提供一些帮助。

2 个答案:

答案 0 :(得分:3)

初始化表单时可以使用计时器。 当计时器到期时,您关闭表格。

Timer time1 = new Timer();
time1.Elapsed += new ElapsedEventHandler(OnTimedEvent);
time1.Interval = 30000; // 30 secs
...
time1.Enabled = true; // Start the timer
message.ShowDialog();

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    // Close your Form
    message.Close();
    // Maybe you could set a variable, that indicates you, that the timer timed out

}

答案 1 :(得分:0)

您必须覆盖ShowDialog()ShowDialog(owner)。当您的节目对话框被调用时,您启动一​​个计时器并转发到base.ShowDialog()。当计时器引发tick事件时,只需调用Close()

这是一个示例实现:

public partial class FormTimed : Form
{
    private String _OriginalText;
    private DateTime _StartTime;
    private Timer _Timer;

    public FormTimed()
    {
        InitializeComponent();
        InitializeTimer();

        Duration = TimeSpan.FromSeconds(10);
    }

    [DefaultValue(typeof(TimeSpan), "00:00:10")]
    public TimeSpan Duration { get; set; }

    public override string Text
    {
        get
        {
            return _OriginalText;
        }
        set
        {
            _OriginalText = value;
            base.Text = value;
        }
    }

    public void DisableTimer()
    {
        _Timer.Stop();
        base.Text = _OriginalText;
    }

    public void ResetTimer()
    {
        _StartTime = DateTime.UtcNow;
        _Timer.Start();
    }

    public new DialogResult ShowDialog()
    {
        StartTimer();
        return base.ShowDialog();
    }

    public new DialogResult ShowDialog(IWin32Window owner)
    {
        StartTimer();
        return base.ShowDialog(owner);
    }

    private void InitializeTimer()
    {
        _Timer = new Timer();
        _Timer.Interval = 100;
        _Timer.Tick += OnTimerTick;
    }

    private void OnTimerTick(object sender, EventArgs e)
    {
        var finishTime = _StartTime + Duration;
        var remainingDuration = finishTime - DateTime.UtcNow;

        if (remainingDuration < TimeSpan.Zero)
        {
            Close();
        }

        base.Text = _OriginalText + " (" + (int)remainingDuration.TotalSeconds + ")";
    }

    private void StartTimer()
    {
        _StartTime = DateTime.UtcNow;
        _Timer.Start();
    }
}