由于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();
}
}
小编推荐: 世界一流大学建设高校是什么意思(解析世界一流大学的定义是什么)Ios11越狱更换微信图标(自定义更换iPhone微信App图标)定义英文(21考研英语高频词汇)