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



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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UltraPanel
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
private void StartAsyncTimedWork()
{
myTimer.Interval = 5000;
myTimer.Tick += new EventHandler(wait);
myTimer.Start();
}
private void wait(object sender, EventArgs e)
{
this.Hide();
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
}

您可以使用Form2的Shown事件,使其成为async,然后从那里使用await您的方法(此处为重映射StartAsync(int interval)(,通过您认为合适的延迟间隔。

Form3是用using语句声明的,因为使用了.ShowDialog():您需要处理该Form。
我添加了this.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可以在延迟生效时关闭:如果你不取消Task.Delay(),即使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();
}
}

最新更新