我目前正在用C#开发一个显示消息框的应用程序。几秒钟后如何自动关闭消息框?
您将需要创建自己的Window,其背后的代码包含如下所示的已加载处理程序和计时器处理程序:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Timer t = new Timer();
t.Interval = 3000;
t.Elapsed += new ElapsedEventHandler(t_Elapsed);
t.Start();
}
void t_Elapsed(object sender, ElapsedEventArgs e)
{
this.Dispatcher.Invoke(new Action(()=>
{
this.Close();
}),null);
}
然后您可以通过调用ShowDialog()使您的自定义消息框出现:
MyWindow w = new MyWindow();
w.ShowDialog();
System.Windows.MessageBox.Show()方法具有一个重载,该重载将所有者Window作为第一个参数。如果我们创建一个不可见的所有者窗口,然后在指定时间后关闭该窗口,则其子消息框也将关闭。
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError=true)]
static extern int MessageBoxTimeout(IntPtr hwnd, String text, String title,
uint type, Int16 wLanguageId, Int32 milliseconds);
MessageBoxTimeout((System.IntPtr)0 ,"Message", "Title",0,0, 1000);
//last parameter timeout in milisecond