C# 使用委托调用待待闪屏。

以前总在博客园看别人写的博客,这是我第一次写技术博客,竟然不知道如何开始。在此向博客园里各位辛勤耕耘的各位博主致敬。

我以前开发Asp.net 程序较多,少有接触WinForm。最近调换了工作,也有机会接触WinForm.首先做WinForm的感觉像是客场作战,好多东西都不大熟悉。所以要加强努力。

废话少说,进入正题。首先说说场景:

程序开发难免会有大数据量操作,在操作大量数据时,有时候需用户等待,在这一段时间内既不想让用户点其它操作,又不像让用户感觉程序假死了。怎么办?对,就是要需使用一个等待的闪屏,告诉用户"数据读取中"旁边还有一个gif动画在转动。等到完成操作时,闪屏自动关闭。

接下来看看效果:

可能会有很多同学笑我了:这么简单的东西,还拿出来写?简单是简单了点儿,可是对于一个WinForm不熟悉的人来说却也费了不少周章。

再接下来是实现方式

1、简单的实体类。(PS:因为是个小Demo 这个实体就没怎么加注释,^_^)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections;

namespace Demo
{
public class Product
{
public int ProductID { set; get; }
public string ProductName { set; get; }
public int Count { set; get; }
public double Pice { set; get; }
public string Uint { set; get; }
}
}

2、等待闪屏:相对简单,没有代码。在窗体上拖了一个Lable控件 和一个PictureBox,把Lable的Text属性设置为:“数据读取中”并且改了一下字体样式,给PictureBox装载一个gif图像

3、主窗体:在主窗体上拉个网格控件(本Demo使用Developer Express的网格控件)、一个按钮:把按钮的Text属性改为 “读取”、一个BindingSource,
下面看主窗体的实现代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.Linq;
using System.Threading;

namespace devDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
frmLoading loading = new frmLoading();//闪屏窗体

#region 委托
/// <summary>
/// 关闭闪屏
/// </summary>
public delegate void Closeloading();
/// <summary>
/// 绑定数据
/// </summary>
/// <param name="ls">数据列表</param>
public delegate void BindedData(List<Product> ls);
#endregion

private void FormMain_Load(object sender, EventArgs e)
{
}

/// <summary>
/// 读取按钮点击事件
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
new Action(ReadData).BeginInvoke(new AsyncCallback(CloseLoading), null);
loading.ShowDialog();//显示loading
}

/// <summary>
/// 读取数据
/// </summary>
public void ReadData()
{
List<Product> productList = new List<Product>();
//装载模拟数据
for (int i = 0; i < 15; i++)
{
productList.Add(new Product
{
ProductID = i + 1,
Count = new Random().Next(i * 10, 3000 / (i + 1)),
Pice = System.Math.Round(new Random().NextDouble() * (i + 1) * 100, 4),
Uint = "",
ProductName = string.Format("产品{0}", i)
});
Thread.Sleep(200);//每添加一条记录休息200毫秒
}

this.Invoke(new BindedData((pls) => {
//绑定数据
this.protuctBindingSource.DataSource = pls;
}),productList);
}

/// <summary>
/// 关闭loading
/// </summary>
/// <param name="ar"></param>
public void CloseLoading(IAsyncResult ar)
{
this.Invoke(new Closeloading(() => { loading.Close(); }));
}
}
}

至此这个Demo完成.若有不足之处,或是有更好的方式,欢迎提出。

另外,写技术博客真不容易。佩服那些一直更新自己博客的老师们。

原文地址:https://www.cnblogs.com/james2010/p/2296531.html