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();
        }
    }
相关推荐
大模型码小白9 分钟前
AI 提示词专栏:使用系统指令(System Prompt)实现全局约束
java·大数据·运维·开发语言·人工智能·python·prompt
HugoStudio_SWAN25 分钟前
C++ CMD 互动动画:按键触发爆炸效果
开发语言·c++·学习·程序人生
互联网中的一颗神经元29 分钟前
10. Large 对象分配:直接路径
开发语言·golang
mayaairi2 小时前
JS BOM完全指南(二):事件轮询、三大尺寸家族与浏览器对象详解
开发语言·javascript·ecmascript
technology_x2 小时前
液冷超充站设备厂家哪家好?2026年功率与散热对比
java·开发语言
SurpriseDPD2 小时前
bpftrace‑tasks 工具代码分析
开发语言·python
千谦阙听2 小时前
C++篇:类和对象(上)
开发语言·c++
许彰午3 小时前
07-SqlBuilder六法
java·开发语言·低代码·架构
BS30813_vx3 小时前
【编号:01652】Spring Boot村务管理系统:财务公开、党建活动与计生服务一体化实战
开发语言·python
Jul1en_3 小时前
【Java 脚手架】封装通用工具类-3
java·开发语言·redis·缓存·ai·bootstrap·rabbitmq