MessageBox提示框自动关闭

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Gnd15732625435/article/details/53301815

第一步:新建一个类库,如图:

这里写图片描述

第二步:添加两个类,CloseState.cs和ShowMsg.cs,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class CloseState
    {
        private int _Timeout;

        /// <summary>
        /// In millisecond
        /// </summary>
        public int Timeout
        {
            get
            {
                return _Timeout;
            }
        }

        private string _Caption;

        /// <summary>
        /// Caption of dialog
        /// </summary>
        public string Caption
        {
            get
            {
                return _Caption;
            }
        }

        public CloseState(string caption, int timeout)
        {
            _Timeout = timeout;
            _Caption = caption;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Model
{
      public class ShowMsg  //自动关闭提示框
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);

        //三个参数:1、文本提示-text,2、提示框标题-caption,3、按钮类型-MessageBoxButtons ,4、自动消失时间设置-timeout
        public  void ShowMessageBoxTimeout(string text, string caption,
            MessageBoxButtons buttons, int timeout)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
                new CloseState(caption, timeout));
            MessageBox.Show(text, caption, buttons);
        }


        private static void CloseMessageBox(object state)
        {
            CloseState closeState = state as CloseState;

            Thread.Sleep(closeState.Timeout);
            IntPtr dlg = FindWindow(null, closeState.Caption);

            if (dlg != IntPtr.Zero)
            {
                IntPtr result;
                EndDialog(dlg, out result);
            }
        }
    }
}

第三步:调用

Model.ShowMsg show = new Model.ShowMsg();
show.ShowMessageBoxTimeout("密码修改成功", "温馨提示", MessageBoxButtons.OK, 1000); //单位毫秒

参考资料:

资料一:http://www.cnblogs.com/XGLSummer/archive/2012/09/06/2673334.html
资料二:http://blog.csdn.net/fuyifang/article/details/46447547

展开阅读全文

没有更多推荐了,返回首页