C# 中 MessageBox 定时关闭

C# 中 MessageBox 定时关闭

WPF中 System.Windows.Forms 的 MessageBox 并未提供定时关闭的功能,所以要实现此目标,需添加一些其他代码,如定时监控等。

需求说明:

  1. 弹出提示框后若一定时间内未点击此提示框,则其自动关闭;
  2. 弹出提示框后若在规定时间内点击该提示框,则正常返回所选选项数据。

代码如下:

public class MessageBoxTimeOut
    {
        private static string _caption;
        private static Timer timer;

        private static void StartTimer(int interval)
        {
            timer = new Timer();
            timer.Interval = interval * 1000;

            timer.Tick += (sender, e) =>
            {
                IntPtr ptr;
                if (CheckMessageBox(out ptr))
                {
                    KillMessageBox(ptr);
                }
                //timer.Enabled = false;
            };
            timer.Enabled = true;
        }

        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, int timeout)
        {
            _caption = caption;
            StartTimer(timeout);

            DialogResult result = MessageBox.Show(text, caption, buttons, icon);
            timer.Stop();
            return result;
        }

        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

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

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool IsWindow(IntPtr hWnd);

        private static bool CheckMessageBox(out IntPtr ptr)
        {
            //ptr = FindWindow(null, _caption); // "#32770" 是 MessageBox 的类名
            ptr = FindWindow("#32770", _caption); 
            return ptr != IntPtr.Zero && IsWindow(ptr);
        }

        private static void KillMessageBox(IntPtr ptr)
        {
            IntPtr res1;
            EndDialog(ptr, out res1);
        }
    }

此时便可正常调用 MessageBox 去弹出定时自动关闭的提示框,代码如下

 //DialogResult result = MessageBox.Show("your message", "title", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
DialogResult result = MessageBoxTimeOut.Show("your message", "title", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, 4);

但需注意,上述只实现了具有返回值的显示方式,没有返回值的提示框显示需微调上述代码。

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值