显示“用户控件正在加载"加载用户控件时的消息 [英] Displaying a "User control is loading" message while loading a User Control

查看:82
本文介绍了显示“用户控件正在加载"加载用户控件时的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 TabStrip 控件的 Winforms 应用程序.在运行时,用户控件将被动态加载到不同的选项卡中.

I have a Winforms Application with a TabStrip Control. During runtime, UserControls are to be loaded into different tabs dynamically.

我想在加载 UserControl 之前和加载完全完成之前向用户显示用户控件 xyz 正在加载"消息(将现有标签设置为可见并更改其文本).

I want to present a "User Control xyz is loading" message to the user (setting an existing label to visible and changing its text) before the UserControl is loaded and until the loading is completely finished.

到目前为止我的方法:

  1. 尝试在 BackgroundWorker 线程中加载用户控件.这失败了,因为我必须在加载 UserControl 期间访问 Gui-Controls
  2. 尝试在 BackgroundWorker 线程中显示消息.这显然失败了,因为 BackgroundWorker 线程不是 UI 线程 ;-)
  3. 显示消息,调用 DoEvents(),加载用户控件.这会导致每次加载 UserControl 时出现不同的行为(闪烁,...),而且我无法控制何时以及如何再次将其设置为不可见.

总结一下,我有两个问题:

To sum it up, I have two questions:

  1. 如何在加载用户控件之前确保消息直接可见
  2. 如何确保在 UserControl 完全加载(包括所有数据绑定、网格格式等)的那一刻再次将消息设置为不可见

推荐答案

我们使用的类似这样:

  1. 创建一个新表单,其中包含您想要向用户显示的任何内容,
  2. 实现一个静态方法,您可以在其中调用要在其内部创建的表单,以防止内存泄漏
  3. 在此表单中创建一个新线程,以便表单在单独的线程中运行并保持响应;我们使用一个 ajax 控件来显示一个填充的进度条.

在用于启动线程的方法中,将其属性设置为 topmost true 以确保它保持在顶部.

within the method you use to start the thread set its properties to topmost true to ensure it stays on top.

例如在您的主表单中执行此操作:

for instance do this in your main form:

loadingForm.ShowLoadingScreen("usercontrollname");
//do something
loadingform.CloseLoadingScreen();

在加载表单类中;

public LoadingScreen()
{
  InitializeComponent();
}

public static void ShowLoadingScreen(string usercontrollname)
{
  // do something with the usercontroll name if desired
  if (_LoadingScreenThread == null)
  {
    _LoadingScreenThread = new Thread(new ThreadStart(DoShowLoadingScreen));
    _LoadingScreenThread.IsBackground = true;
    _LoadingScreenThread.Start();
  }
}

public static void CloseLoadingScreen()
{
  if (_ls.InvokeRequired)
  {
    _ls.Invoke(new MethodInvoker(CloseLoadingScreen));
  }
  else
  {
    Application.ExitThread();
    _ls.Dispose();
    _LoadingScreenThread = null;
  }
}

private static void DoShowLoadingScreen()
{
    _ls = new LoadingScreen();
    _ls.FormBorderStyle = FormBorderStyle.None;
    _ls.MinimizeBox = false;
    _ls.ControlBox = false;
    _ls.MaximizeBox = false;
    _ls.TopMost = true;
    _ls.StartPosition = FormStartPosition.CenterScreen;

  Application.Run(_ls);
}

这篇关于显示“用户控件正在加载"加载用户控件时的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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