C# 从启动表单到切换到另一表单,请等待5秒钟

C# 从启动表单到切换到另一表单,请等待5秒钟,c#,.net,winforms,wait,C#,.net,Winforms,Wait,我想制作一个表单,在切换到另一个表单之前,在屏幕上显示一个文本块5秒钟。用按钮切换是可行的,但5秒钟后如何切换?这就是我所拥有的 使用制度; 使用System.Collections.Generic; 使用系统组件模型; 使用系统数据; 使用系统图; 使用System.Linq; 使用系统文本; 使用System.Threading.Tasks; 使用System.Windows.Forms; 命名空间超面板 { 公共部分类表单2:表单 { 公共表格2 { 初始化组件; } private Sy

我想制作一个表单,在切换到另一个表单之前,在屏幕上显示一个文本块5秒钟。用按钮切换是可行的,但5秒钟后如何切换?这就是我所拥有的

使用制度; 使用System.Collections.Generic; 使用系统组件模型; 使用系统数据; 使用系统图; 使用System.Linq; 使用系统文本; 使用System.Threading.Tasks; 使用System.Windows.Forms; 命名空间超面板 { 公共部分类表单2:表单 { 公共表格2 { 初始化组件; } private System.Windows.Forms.Timer myTimer=新的System.Windows.Forms.Timer; 私人无效StartSyncTimedWork { myTimer.Interval=5000; myTimer.Tick+=neweventhandlerwait; myTimer.Start; } 私有void waitobject发送方,事件参数e { 这个。隐藏; Form3 f3=新的Form3; f3.ShowDialog; } } } 您可以使用所显示的Form2事件,使其异步,然后在此等待您的方法,从那里返回StartAsyncint间隔,传递您认为合适的延迟间隔

Form3是用using语句声明的,因为使用了.ShowDialog:您需要处理该表单。 我添加了这个。Show在Form3关闭时再次显示Form2

using System.Threading.Tasks;

private async void Form2_Shown(object sender, EventArgs e)
{
    await StartAsync(5000);
}

private async Task StartAsync(int interval)
{
    await Task.Delay(interval);
    this.Hide();
    using (var f3 = new Form3()) {
        f3.ShowDialog();
    }
    this.Show();
}
如果在延迟进行时可以关闭Form2,则会有更大的成就:如果不取消任务。延迟,即使Form2显然已经关闭,也会显示Form3:

private CancellationTokenSource cts = null;

private async void Form2_Shown(object sender, EventArgs e)
{
    cts = new CancellationTokenSource();
    try {
        await StartAsync(5000, cts.Token);
    }
    catch (TaskCanceledException) {
        // Do whatever you see fit here
        Console.WriteLine("Canceled");
    }
    finally {
        cts.Dispose();
        cts = null;
    }
}

private async Task StartAsync(int interval, CancellationToken token)
{
    await Task.Delay(interval, token);
    this.Hide();
    using (var f3 = new Form3()) {
        f3.ShowDialog();
    }
    this.Show();
}

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    if (cts != null) {
        cts.Cancel();
    }
}

将StartAsyncTimedWork添加到构造函数Form2或formloaded方法。同样在等待中添加myTimer.stop;