初始屏幕完成后台处理后显示主窗体

时间:2018-08-04 15:55:56

标签: c# winforms

是否可以仅显示初始屏幕(不显示主窗体)?

SplashScreen splash;

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    splash = new SplashScreen();
    splash.Show();

    BackgroundWorker backgroundWorker = new BackgroundWorker();
    backgroundWorker.DoWork += BackgroundWorker_DoWork;
    backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
    backgroundWorker.RunWorkerAsync();

    // var mainForm = MainForm();
    // Application.Run(layoutForm); // I don't want to call this from here
}


private static void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     splash.Close();
     // This never gets called, coz application ended
}

private static void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 0; i <= 100; i++)
    {
        Thread.Sleep(100);
    }
}

1 个答案:

答案 0 :(得分:1)

您将从主窗体调用启动屏幕。

public partial class mainform : Form
{
    public mainform()
    {
        InitializeComponent();
    }

    public mainform_Load(object sender, EventArgs e)
    {
        this.Visible = false;
        using (SplashScreen ss = new SplashScreen())
        {
            ss.ShowDialog();
            SetTheme(ss.LoadedTheme);
            this.Visible = true;
        }
    }

    private void SetTheme(Theme theme)
    {
        //Put your theme setting code here.
    }
}

以下是您的SplashScreen代码的外观:

public partial class SplashScreen : Form
{
    public Theme LoadedTheme { get; private set; }

    public SplashScreen()
    {
        InitializeComponent();
    }

    public void SplashScreen_Load(object sender, EventArgs e)
    {
        bwSplashScreenWorker.RunWorkerAsync();
    }

    public void bwSplashScreenWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Load in your data here
        LoadedTheme = LoadTheme();
    }

    public void bwSplashScreenWorker_Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        DialogResult = DialogResult.OK;
    }
}

现在,您的应用程序将启动,在加载主窗体时,它将隐藏自身,以阻止方式打开SplashScreen。初始屏幕将在后台线程中加载主题数据,并将其保存到LoadedTheme属性中。后台工作人员完成操作后,将DialogResult设置为OK,这将关闭SplashScreen,并将控件返回到mainform_Loaded。此时,您将调用SetTheme方法,将其从SplashScreen传入公共属性LoadedTheme。您的SetTheme方法设置您的主题,并返回到mainform_Loaded,在此它将主窗体设置为可见。