在 WPF 窗口 C# 的消息框中显示 5 秒倒数计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23879885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display a 5 sec countdown timer in a messagebox in a WPF window C#
提问by Tak
I want to Display a messagebox with no buttons for 5 secs in a WPF application, where the text in the message box will change every sec, like in the first sec it will be "5 sec remaining" the next will be "4 sec remaining",... and when it reaches zero then the messagebox will disappear. So if anyone could please advise how to do this.
我想在 WPF 应用程序中显示一个没有按钮的消息框 5 秒,其中消息框中的文本将每秒钟更改一次,就像在第一秒中它将是“5 秒剩余”接下来将是“4 秒剩余” ",... 当它达到零时,消息框将消失。因此,如果有人可以请建议如何做到这一点。
采纳答案by Tak
I've followed the solution found here
我已经按照这里找到的解决方案
A class was created shown below:
创建了一个类,如下所示:
class AutoClosingMessageBox
{
System.Threading.Timer _timeoutTimer;
string _caption;
AutoClosingMessageBox(string text, string caption, int timeout)
{
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
MessageBox.Show(text, caption);
}
public static void Show(string text, string caption, int timeout)
{
new AutoClosingMessageBox(text, caption, timeout);
}
void OnTimerElapsed(object state)
{
IntPtr mbWnd = FindWindow(null, _caption);
if (mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
}
const int WM_CLOSE = 0x0010;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
then it was called using :
然后它被称为使用:
AutoClosingMessageBox.Show("waiting", "wait...", 1000);
回答by SKall
This isn't the most elegant solution but it should at least get your started:
这不是最优雅的解决方案,但至少应该让您开始:
public partial class MessageWindow : Window
{
private MessageWindow()
{
InitializeComponent();
}
public static void Show(string text, string caption, int timeout)
{
var msgWindow = new MessageWindow()
{
Title = caption
};
Task.Factory.StartNew(() =>
{
for (var n = 0; n < timeout; n++)
{
msgWindow.Dispatcher.Invoke(() =>
{
msgWindow.text.Text = string.Format("{0}{1}{2}s left...", text, Environment.NewLine, timeout - n);
});
System.Threading.Thread.Sleep(1000);
}
msgWindow.Dispatcher.Invoke(msgWindow.Close);
});
msgWindow.ShowDialog();
}
}

