C# 构建可定时关闭的异步提示弹窗

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();
        }
    }
相关推荐
方也_arkling6 小时前
【Java-Day08】static / final / 枚举
java·开发语言
风吹夏回6 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei117 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1127 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding7 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋97 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
xiaoshuaishuai87 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024068 小时前
SVN 检出操作
开发语言
basketball6168 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
旺仔来了9 小时前
不联网的Linux下部署python环境
linux·开发语言·python