C# winform自定义可定时关闭的MessageBox

由于MessageBox.Show会阻断线程,如果长时间不关闭MessageBox对话框,某些情况下会导致程序异常退出,所以我们需要一个可以定时自动退出的MessageBox。

实现起来效果如何呢,请看图

定时关闭的MessageBox

实现起来其实很简单,通过自定义Form对象很容易实现窗口效果,定时关闭通过一个Timer来倒计时,时间到时通过设置form的DialogResult来结束MessageBox对话框。

看代码吧

WInform定时关闭的MessageBox代码

惯例,献上可复制的代码

public static class MessageBoxHelper    {        public static DialogResult ShowWarning(string text, string caption)        {            var form = new Form()            {                Width = 640,                Text = caption,                ControlBox = false,                FormBorderStyle = FormBorderStyle.FixedDialog,                StartPosition = FormStartPosition.CenterScreen,                ShowInTaskbar = false            };            Label contentView = new Label()            {                Padding = new Padding(20),                Text = text,                Dock = DockStyle.Fill,                BackColor = Color.White,                TextAlign=ContentAlignment.MiddleLeft            };            Panel panel = new Panel()            {                BackColor = ColorTranslator.FromHtml("#ccccc"),                Height = 64,                Dock = DockStyle.Bottom,            };            System.Timers.Timer timer = new System.Timers.Timer(1000);            Button button = new Button()            {                Text = "OK",                Height =48,                Width=120,                AutoSize=false            };            button.Top = 8;            button.Left = 640 - button.Width-35;            button.Click += (s, e) =>            {                timer.Stop();                timer.Dispose();                form.DialogResult = DialogResult.OK;            };            panel.Controls.Add(button);            form.Controls.Add(contentView);            form.Controls.Add(panel);                        int seconds = 5;            timer.Elapsed+=(s, e) => {                button.Invoke(() => {                    if (seconds < 0)                    {                        button.PerformClick();                    }                    button.Text = #34;OK({seconds}s)";                    seconds--;                });                            };            timer.Start();            return form.ShowDialog();        }    }
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章