.NET-MessageBox延时一定时间自动关闭

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/daigualu/article/details/70859194
   public class MsgBoxHelper
    {
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        private const int WM_CLOSE = 0x10;

        public static  void IntelligentClose(string boxCaption)
        {
            Timer timer = new Timer();
            timer.Interval = 3000;    //3秒后关闭窗体
            timer.Tick += (sender, args) =>
            {
                //查找MessageBox的弹出窗口,注意MessageBox对应的标题
                IntPtr ptr = FindWindow(null, boxCaption);
                if (ptr != IntPtr.Zero)
                {
                    //查找到窗口则关闭
                    PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                }
                (sender as Timer).Stop(); //停止计时器
            }; 
            timer.Start();
        }

    }

使用方法:

MsgBoxHelper.IntelligentClose("Baidu Message");
MessageBox.Show("这是一个智能关闭的窗体!", "Baidu Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
展开阅读全文

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