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();
        }
    }
相关推荐
nvvas3 分钟前
Java 入门(四):数组——数据的集合管理
java·开发语言
Y3815326621 小时前
SERP 数据清洗实战:字段标准化、日期解析与去重键
开发语言·数据库·python·python数据库
君顾11 小时前
本地城市低空经济管理系统定制:城市级低空运营平台架构与落地实战
java·开发语言·飞手
多多鼠2 小时前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
WiChP2 小时前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
孙启超3 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
开发语言·后端·rust
2501_933670793 小时前
经营财务岗技能栈拆解:Excel、SQL、BI、预算分析怎么准备
开发语言
数据狐(Datafox)4 小时前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
宝桥南山4 小时前
Microsoft Fabric - 简单尝试一下Microsoft Fabric .NET SDK
microsoft·微软·.net·.netcore·powerbi·fabric
专注仿真4 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类