public static class MessageBoxAutoClose
        {
            // 引入Windows API函数
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

            [System.Runtime.InteropServices.DllImport("user32.dll")]
            private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);

            private const int WM_CLOSE = 0x0010;

            public static void Show(string message, string title, int delayMilliseconds)
            {
                System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
                timer.Interval = delayMilliseconds;
                int coui = delayMilliseconds / 1000;
                timer.Tick += (sender, e) =>
                {
                    timer.Stop();
                    IntPtr mbWnd = FindWindow("#32770", title); // 根据标题查找消息框的窗口句柄
                    if (mbWnd != IntPtr.Zero)
                    {
                        SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); // 发送关闭消息框的消息
                    }
                };
                timer.Start();

                MessageBox.Show(message + "(" + coui + "秒自动确定)", title);
            }

        }

更多推荐