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

   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);

你可能感兴趣的:(.NET基础,.NET开发)