在设计应用程序过程中,有时候加载对象需时较长,我们可以显示一个Loading等待页面,对用户来说就比较友好了。

这个还是涉及到多线程,下面是步骤。
一、创建好Loading窗体:

一个Panel用于显示转圈动画(仿Win10的Loading),一个Loading文本标签。动画的代码来自网络。
public partial class Fm20Loading : Form { public Fm20Loading() { InitializeComponent(); //LblMessage.Text = MultiLang.Surface(null, "OnLoading", "目标对象正在加载中, 请您稍等..."); SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); //初始化绘图timer _tmrGraphics = new UITimer { Interval = 1 }; //Invalidate()强制重绘,绘图操作在OnPaint中实现 _tmrGraphics.Tick += (sender, e) => PnlImage.Invalidate(false); _dotSize = PnlImage.Width / 10f; //初始化"点" _dots = new LoadingDot[5]; Color = Color.CadetBlue; } /// <summary> /// 构造器 /// </summary> /// <param name="message"></param> public Fm20Loading(string message) { InitializeComponent(); //双缓冲,禁擦背景 SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); //初始化绘图timer _tmrGraphics = new UITimer { Interval = 1 }; //Invalidate()强制重绘,绘图操作在OnPaint中实现 _tmrGraphics.Tick += (sender, e) => PnlImage.Invalidate(false); _dotSize = PnlImage.Width / 10f; //初始化"点" _dots = new LoadingDot[5]; Color = Color.CadetBlue; Message = message; } private void Fm20Loading_Load(object sender, EventArgs e) { LblMessage.ForeColor = Color; if (Owner != null) { StartPosition = FormStartPosition.Manual; Location = new Point(Owner.Left, Owner.Top); Width = Owner.Width; Height = Owner.Height; } else { var screenRect = Screen.PrimaryScreen.WorkingArea; Location = new Point((screenRect.Width - Width) / 2, (screenRect.Height - Height) / 2); } Start(); } private void Fm20Loading_Shown(object sender, EventArgs e) { if (_workAction != null) { _workThread = new Thread(ExecWorkAction) { IsBackground = true }; _workThread.Start(); } } #region 属性 [Description("消息")] public string Message { get { return LblMessage.Text; } set { LblMessage.Text = value; } } [Browsable(false), Description("圆心")] public PointF CircleCenter => new PointF(PnlImage.Width / 2f, PnlImage.Height / 2f); [Browsable(false), Description("半径")] public float CircleRadius => PnlImage.Width / 2f - _dotSize; [Browsable(true), Category("Appearance"), Description("设置\"点\"的前景色")] public Color Color { get; set; } #endregion 属性 #region 字段 [Description("工作是否完成")] public bool IsWorkCompleted; [Description("工作动作")] private ParameterizedThreadS

本文介绍了如何在C# Winform应用中创建一个加载等待页面,以提高用户体验。通过设置一个包含转圈动画和文本标签的Panel,结合多线程技术,在加载耗时对象时显示。调用适当的代码,可以灵活地在需要的时候显示和关闭这个加载等待页面,满足大多数友好提示界面的需求。
最低0.47元/天 解锁文章
4439

被折叠的 条评论
为什么被折叠?



