You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForms如何实现5秒自动从启动窗体切换到应用窗体?

实现启动界面5秒后跳转至主界面的C#解决方案

我正在制作一个操作系统,需要程序在5秒后从启动界面(Form1)切换到包含所有应用的主界面(Form2),以下是我尝试的两段代码,但第二段没有效果:

第一段尝试的代码

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 Byte_OS_1._0_Interface_Test_5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

        private async void Form1_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            await Task.Delay(5000);
            this.Hide();
            Form2 home = new Form2();
            home.Show();
        }
    }

}

第二段无效的代码

static async void Main()
{
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
     await Task.Delay(5000);
     Application.Run(new Form2());
}

代码问题分析

  • 第二段代码无效的核心原因:Application.Run(new Form1())会阻塞主线程,直到Form1被关闭才会执行后续代码,因此延迟和启动Form2的逻辑永远不会触发。
  • 第一段代码的逻辑本身是可行的,但用Hide()隐藏Form1会导致该窗体仍占用内存资源,建议改为Close()直接关闭。

优化后的可行代码

using System;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace Byte_OS_1._0_Interface_Test_5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            // 设置启动界面为无边框最大化
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            
            // 等待5秒
            await Task.Delay(5000);
            
            // 关闭启动界面并打开主界面
            this.Close();
            Form2 home = new Form2();
            // 可选:主界面关闭时退出整个应用
            home.FormClosed += (s, args) => Application.Exit();
            home.Show();
        }
    }
}

额外说明

如果需要保持应用的标准启动流程,也可以修改Main方法,使用非阻塞的方式显示启动界面:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    
    Form1 splash = new Form1();
    splash.Show();
    
    // 异步等待并切换界面
    _ = SwitchToMainForm(splash);
    
    Application.Run();
}

private static async Task SwitchToMainForm(Form splashForm)
{
    await Task.Delay(5000);
    splashForm.Close();
    
    Form2 mainForm = new Form2();
    mainForm.FormClosed += (s, args) => Application.Exit();
    mainForm.Show();
}

内容的提问来源于stack exchange,提问作者ourenia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:13:10