C# 构建可定时关闭的异步提示弹窗
引言
我们在最常用最简单的提示弹框莫过于MessageBox.Show( )的方法了,但是使用久了之后,你会发现这个MessageBox并不是万能的,有事后并不想客户去点击,或者因为非异步运行,而卡住当前线程的运行,于是,就产生了一个只需要提示不需要点击确认的异步弹框需求。这里我就介绍一种较为简单的实现方法。
1、调用接口的实现
可以看到ShowMsg类中定义了三个函数,,第一个Show()函数异步运行控制一个新的窗体生成,另外两个则是用户调用它的接口函数,为了方便,我们可以固定延时时间参数也可以控制延时参数。
c
/// <summary>
/// 消息框调用接口
/// </summary>
public class ShowMsg {
internal static System.IAsyncResult Show(Form form, string info, int timeout)
{
if (form == null)
return null;
//Lambda表达式异步弹出消息窗体
System.IAsyncResult result = form.BeginInvoke(new MethodInvoker(() => {
frShowMsg show = new frShowMsg(info, timeout);
show.ShowDialog(form);
show.Dispose();
show = null;
}));
return result;
}
//固定延时弹信息窗
internal static void Show(System.Windows.Forms.Form form, string info)
{
Show(form, info, 1000);
}
//不固定延时弹信息窗
internal static void Show_timeout(System.Windows.Forms.Form form, string info, int timeout)
{
Show(form, info, timeout);
}
}
2、自动定时窗口的实现
可以看到下面的程序中我们建立了一个Form窗体,在窗体中我们除了定义了一些我们需要显示的属性,同时,也定义和启动了一个timer窗体定时器,等待定时器完成一次定时后进入tick,停止定时器以及关闭当前窗体Close()。最后回到show.Dispose()完成析构。
c
/// <summary>
/// 弹出自动消失消息框
/// </summary>
public partial class frShowMsg : Form {
public frShowMsg(string info, int timeout) {
InitializeComponent();
this.TopMost = true;
this.StartPosition = FormStartPosition.CenterParent;
lbMsg.Text = info;
timer.Interval = timeout;
timer.Start();
}
private void close() {
timer.Stop();
this.Close();
}
private void timer_Tick(object sender, EventArgs e) {
close();
}
}