简体   繁体   English

如何打开表单,然后在C#上X秒钟后将其关闭?

[英]How to open a form and then close it after X amount of seconds on c#?

I need to open a form on C# and then have it close automatically after, say, 5 seconds.. The thing is, I need the form to be closed from the form it was opened from because the form I am opening is sometimes opened from another form without being automatically closed. 我需要在C#上打开一个表单,然后在5秒后自动关闭它。问题是,我需要从打开它的表单中关闭该表单,因为有时我要打开的表单是从另一种形式而不会自动关闭。

I've tried this: 我已经试过了:

        private void button6_Click(object sender, EventArgs e)
    {
        GetNumber gtn = new GetNumber();
        gtn.Show();
        System.Threading.Thread.Sleep(6000);
        gtn.Hide();
        gtn = null;
    }

But the form was messed up when it started, same happened when I tried with a timer. 但是表单在启动时就搞砸了,当我尝试使用计时器时也是如此。 Anybody know how to solve my problem? 有人知道如何解决我的问题吗?

As itsme86 said, timers would work for what you are trying to do. 就像itsme86所说的那样,计时器会为您要尝试的工作。 If you are in .Net 4.5 or greater you can use the async/await features. 如果您使用的是.Net 4.5或更高版本,则可以使用异步/等待功能。

At its core, you need to free up the UI thread to continue on its way. 从本质上讲,您需要释放UI线程以继续前进。 Your Thread.Sleep is putting the UI thread out of commission. 您的Thread.Sleep正在使UI线程退出使用。 Using a timer or the async/await allows the UI thread to launch your dialog and process any user actions. 使用计时器或异步/等待允许UI线程启动对话框并处理任何用户操作。

private async void button6_Click(object sender, EventArgs e)
{
    GetNumber gtn = new GetNumber();
    gtn.Show();
    await Task.Delay(6000);
    gtn.Hide();
    gtn = null;
}

A timer would be the correct approach: 计时器是正确的方法:

private void button6_Click(object sender, EventArgs e)
{
    GetNumber gtn = new GetNumber();
    gtn.Show();

    System.Timers.Timer timer = new Timer(6000);
    timer.Elapsed += (_, _2) => { Invoke((MethodInvoker)delegate { gtn.Close(); }); };
    timer.Start();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM