C#WinForm-加载屏幕 [英] C# WinForm - loading screen

查看:293
本文介绍了C#WinForm-加载屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下如何制作一个加载屏幕(只是一张图片或其他东西),该屏幕在加载程序时出现,并在加载完成后消失.

I would like to ask how to make a loading screen (just a picture or something) that appears while the program is being loaded, and disappears when the program has finished loading.

在更高级的版本中,我看到了显示的进度条(%).您怎么拥有它,以及如何计算要显示在其上的百分比?

In fancier versions, I have seen the process bar (%) displayed. how can you have that, and how do you calculate the % to show on it?

我知道有一个Form_Load()事件,但是在任何地方都看不到Form_Loaded()事件或%作为属性/属性.

I know there is a Form_Load() event, but I do not see a Form_Loaded() event, or the % as a property / attribute anywhere.

推荐答案

所有您需要创建一个表单作为初始屏幕并显示它,然后再开始主要显示登录页面,并在加载登录页面后关闭此初始屏幕.

all you need to create one form as splash screen and show it before you main start showing the landing page and close this splash once the landing page loaded.

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

namespace MyTools
{
    public class SplashForm : Form
    {
        //Delegate for cross thread call to close
        private delegate void CloseDelegate();

        //The type of form to be displayed as the splash screen.
        private static SplashForm splashForm;

        static public void ShowSplashScreen()
        {
            // Make sure it is only launched once.    
            if (splashForm != null) return;
            splashForm = new SplashScreen();
            Thread thread = new Thread(new ThreadStart(SplashForm.ShowForm));
            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        static private void ShowForm()
        {
            if (splashForm != null) Application.Run(splashForm);
        }

        static public void CloseForm()
        {
            splashForm?.Invoke(new CloseDelegate(SplashForm.CloseFormInternal));
        }

        static private void CloseFormInternal()
        {
            if (splashForm != null)
            {
               splashForm.Close();
               splashForm = null;
            };
        }
    }
}

和主程序功能如下:

[STAThread]
static void Main(string[] args)
{
    SplashForm.ShowSplashScreen();
    MainForm mainForm = new MainForm(); //this takes ages
    SplashForm.CloseForm();
    Application.Run(mainForm);
}

别忘了在主表单中添加表单加载事件:

Don't forget to add a form load event to your main form:

private void MainForm_Load(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Minimized; 
    this.WindowState = FormWindowState.Normal;
    this.Focus(); this.Show();
}

隐藏初始屏幕后,它将主窗体显示在前台.

It will bring the main form to the foreground after hiding the splash screen.

这篇关于C#WinForm-加载屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆