可设置指定时间自己主动消失的 MessageBox实现

本文主要是讲怎样实现可设置指定时间自己主动消失的 MessageBox提示框ShowMessageBoxTimeout实现;

在开发client应用程序的时候。经经常使用得WinForm中MessageBox提示框。可是有时候还是满足不了一些用户要求,客户要求千奇百怪,比如客户须要做某些提示的时候。不去点击确定或取消的时候,等待一段时间自己主动消失,为此我们能够使用以下类来实现,採用 Thread.Sleep来关掉当前提示框,详细代码例如以下:

ShowMessageBoxTimeout实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Threading;

namespace Tools.App
{
    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 static 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);
            }
        }
    }
}

ShowMessageBoxTimeout调用

//三个參数:1、文本提示。2、提示框标题。3、按钮类型,4、自己主动消失时间设置
ShowMsg.ShowMessageBoxTimeout("欢迎使用数据导出服务程序,本程序默认最小化到电脑托盘,1分钟后正式启动。", 
"程序启动温馨提示-窗体1分钟内无操作会自己主动关闭", MessageBoxButtons.OK, 1000 * 60 * 1);

希望以上分享对初学朋友有些帮助。谢谢!
很多其它关注付义方技术博客:http://blog.****.net/fuyifang
或者直接用手机扫描二维码查看很多其它博文:
可设置指定时间自己主动消失的 MessageBox实现