在MainFrom初始化时progressBar

G B*_*dal 3 c# winforms

我有一个Windows窗体应用程序,需要在加载主窗口之前加载一堆东西.我认为这样做是合理的ProgressBar,所以我想我会显示另一个包含ProgressBar Control使用我的主窗体构造函数的表单.

一切正常但如果我尝试将文本Label放在介绍表单中,其内容将不会显示,直到加载主表单.除了首先加载介绍窗口之外,这里有一种方法可以避免这种情况吗?

Fre*_*örk 5

警告:此帖子包含自我推销的元素; o)

在这种情况下,我可能会使用泼溅形式.我刚才写了一篇博客文章(由此SO Q&A引发)关于一个可以一起使用的线程安全的初始化表单将长期运行的主表单初始化.

简而言之,方法是使用ShowDialog,但是在单独的线程上创建和显示表单,以便它不会阻塞主线程.表单包含状态消息标签(当然也可以使用进度条进行扩展).然后有一个静态类,它提供了用于显示,更新和关闭splash表单的线程安全方法.

压缩代码示例(对于注释代码示例,请查看博客文章):

using System;
using System.Windows.Forms;
public interface ISplashForm
{
    IAsyncResult BeginInvoke(Delegate method);
    DialogResult ShowDialog();
    void Close();
    void SetStatusText(string text);
}

using System.Windows.Forms;
public partial class SplashForm : Form, ISplashForm
{
    public SplashForm()
    {
        InitializeComponent();
    }
    public void SetStatusText(string text)
    {
        _statusText.Text = text;
    }
}

using System;
using System.Windows.Forms;
using System.Threading;
public static class SplashUtility<T> where T : ISplashForm
{
    private static T _splash = default(T);
    public static void Show()
    {
        ThreadPool.QueueUserWorkItem((WaitCallback)delegate
        {
            _splash = Activator.CreateInstance<T>();
            _splash.ShowDialog();
        });
    }

    public static void Close()
    {
        if (_splash != null)
        {
            _splash.BeginInvoke((MethodInvoker)delegate { _splash.Close(); });
        }
    }

    public static void SetStatusText(string text)
    {
        if (_splash != null)
        {
            _splash.BeginInvoke((MethodInvoker)delegate { _splash.SetStatusText(text); });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

SplashUtility<SplashForm>.Show();
SplashUtility<SplashForm>.SetStatusText("Working really hard...");
SplashUtility<SplashForm>.Close();
Run Code Online (Sandbox Code Playgroud)