Winform开发过程中,会遇到长时间执行的情况,这时希望有一个等待框出现,提示用户“操作正在进行,请稍后”之类的信息。我们可以写一个Form窗体,在需要的时候show出来,上面放一个gif图片或执行绘制代码。但问题来了,如果这个等待窗体放在主进程上,遇到长时间执行的代码,gif图片卡死,绘制过程也执行不下去了。
这时我们需要在子线程中创建这个等待窗体,在需要显示等待框的时候,通知他显示,不需要的时候通知关闭。在Main函数中我们看到这样一行代码:
Application.Run(new MainForm());
我们是否可以在一个子线程中这样创建窗体呢?答案是:可行。
主窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread(() => { Application.Run(new Form2()); }) { IsBackground = true }.Start();
}
private void button1_Click(object sender, EventArgs e)
{
Form2.Instance.ShowForm();
}
private void button2_Click(object sender, EventArgs e)
{
Form2.Instance.HideForm();
}
private void button3_Click(object sender, EventArgs e)
{
Form2.Instance.ShowInformation(DateTime.Now.ToString());
}
}
}
等待框窗体:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
Instance = this;
ShowInTaskbar = false;
}
public static Form2 Instance = null;
private void Form2_Load(object sender, EventArgs e)
{
TopMost = true;
}
public void ShowInformation(string info)
{
Invoke(new Action(() =>
{
label1.Text = info;
}));
}
internal void ShowForm()
{
Invoke(new Action(() =>
{
Activate();
WindowState = FormWindowState.Normal;
Show();
}));
}
internal void HideForm()
{
Invoke(new Action(() => { Hide(); }));
}
}
}
最后
以上就是冷酷黄豆最近收集整理的关于Winform创建等待框的全部内容,更多相关Winform创建等待框内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复