C# 在WPF窗口C的消息框中显示5秒倒计时计时器#
我想在WPF应用程序中显示一个5秒钟内没有按钮的messagebox,其中messagebox中的文本每秒钟都会更改一次,就像在第一秒钟,它将是“剩余5秒”,下一秒将是“剩余4秒”,。。。当它达到零时,messagebox将消失。因此,如果有人能提供建议,请提供解决方法。这不是最优雅的解决方案,但至少应该让您开始:C# 在WPF窗口C的消息框中显示5秒倒计时计时器#,c#,wpf,C#,Wpf,我想在WPF应用程序中显示一个5秒钟内没有按钮的messagebox,其中messagebox中的文本每秒钟都会更改一次,就像在第一秒钟,它将是“剩余5秒”,下一秒将是“剩余4秒”,。。。当它达到零时,messagebox将消失。因此,如果有人能提供建议,请提供解决方法。这不是最优雅的解决方案,但至少应该让您开始: public partial class MessageWindow : Window { private MessageWindow() { Ini
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();
}
}
public部分类MessageWindow:Window
{
私有消息窗口()
{
初始化组件();
}
公共静态无效显示(字符串文本、字符串标题、int超时)
{
var msgWindow=新消息窗口()
{
标题=标题
};
Task.Factory.StartNew(()=>
{
对于(变量n=0;n
{
msgWindow.text.text=string.Format(“{0}{1}{2}的左侧…”,text,Environment.NewLine,timeout-n);
});
系统线程线程睡眠(1000);
}
msgWindow.Dispatcher.Invoke(msgWindow.Close);
});
msgWindow.ShowDialog();
}
}
我遵循找到的解决方案
创建了一个类,如下所示:
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);
}
然后它被称为使用:
AutoClosingMessageBox.Show("waiting", "wait...", 1000);
堆栈溢出不是代码编写服务。您需要尝试一个解决方案,并发布您在编写代码时遇到的任何问题。谢谢您的评论。我完全理解,但我对WPF非常陌生,我请求帮助,因为我相信这不是一个非常复杂的问题,这就是为什么我请求比我更有经验的人提供帮助。如果不复杂,而且你是这项技术的新手,为什么不亲自尝试呢?通过尝试比复制粘贴学到更多的东西。编程的本质是实验。我用一个不起作用的解决方案更新了这个问题。答案在[这里][1]找到了,谢谢你的建议![1]: