public partial class MsgBox : ChildWindow
{
int defaultTime = 3;//默认N秒
string userTitle;
DispatcherTimer timer;//定时器
Action<bool> callBackEvent;
bool autoOKConfirm = true;
public MsgBox()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
this.Closed += new EventHandler(MsgBox_Closed);
}
void MsgBox_Closed(object sender, EventArgs e)
{
//待实现
}
void timer_Tick(object sender, EventArgs e)
{
Title = string.Format(userTitle + " [倒计时自动确定:{0}秒]", defaultTime);
defaultTime--;
if (defaultTime == 0)
{
ResetTimer();
if (autoOKConfirm)
{
OKButton_Click(null, null);
}
else
{
CancelButton_Click(null, null);
}
}
}
void ResetTimer()
{
timer.Stop();
defaultTime = 3;
}
public void Show(string msg, string title)
{
Show(msg, title, defaultTime, null, true, MessageBoxButton.OK);
}
public void Show(string msg, string title, int timeSecond, Action<bool> callBack)
{
Show(msg, title, timeSecond, callBack, false, MessageBoxButton.OKCancel);
}
public void Show(string msg, string title, int timeSecond, Action<bool> callBack, bool autoOK, MessageBoxButton button)
{
tbMsg.Text = msg;
userTitle = title;
if (button == MessageBoxButton.OK)
{
OKButton.Content = "确定";
CancelButton.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
CancelButton.Visibility = System.Windows.Visibility.Visible;
OKButton.Content = "同意";
CancelButton.Content = "拒绝";
}
defaultTime = timeSecond;
autoOKConfirm = autoOK;
callBackEvent = callBack;
Show();
timer.Start();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
}