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();
        }
    }
相关推荐
Zhou1411366 分钟前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅40 分钟前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿2 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
hiahiahia1232 小时前
实现完整 Tool Dispatcher
开发语言·前端
AC赳赳老秦2 小时前
公开音频转写信息提取:OpenClaw 处理发布会与听证会文本并提取核心决策信息
大数据·开发语言·汇编·数据库·人工智能·deepseek·openclaw
@yanyu6663 小时前
C编译器安装与第一个C程序
c语言·开发语言
落魄实习生3 小时前
Agent Scope Java 2.x 系列【2】 ReActAgent
java·开发语言
智鸟科技GemeOpen开发者智能设备3 小时前
智能插座二次开发如何接入Home Assistant,从零开始完整工程实现(Python+React)
开发语言·python·物联网·react.js·智能家居