gpt4 book ai didi

c# - progressBar 而 MainFrom 初始化

转载 作者:行者123 更新时间:2023-11-30 14:04:41 25 4
gpt4 key购买 nike

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

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

最佳答案

警告:这篇文章包含 self 推销的元素;o)

在这种情况下,我可能会使用启动形式。我写了a blog post不久前(由 this SO Q&A 触发)关于可以一起使用的线程安全启动窗体将长时间运行的主窗体初始化。

简而言之,该方法是使用 ShowDialog,但在单独的线程上创建和显示表单,这样它就不会阻塞主线程。该表单包含一个状态消息标签(当然也可以使用进度条进行扩展)。然后是一个静态类,它提供线程安全的方法来显示、更新和关闭启动窗体。

精简代码示例(有关注释代码示例,请查看博客文章):

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); });
}
}
}

使用示例:

SplashUtility<SplashForm>.Show();
SplashUtility<SplashForm>.SetStatusText("Working really hard...");
SplashUtility<SplashForm>.Close();

关于c# - progressBar 而 MainFrom 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1321732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com