【问题标题】:Automatically close messagebox in C#在 C# 中自动关闭消息框
【发布时间】:2010-12-06 00:29:28
【问题描述】:

我目前正在用 C# 开发一个应用程序,我在其中显示一个 MessageBox。如何在几秒钟后自动关闭消息框?

【问题讨论】:

  • 确实 - 一个计时器 - 以及您自己的自定义对话框而不是 MessageBox,否则您将不得不开始摆弄向 MessageBox 发送事件以使其关闭,我想。
  • 对于 C++ 看看这个stackoverflow.com/a/66004457/6219626

标签: c# wpf messagebox


【解决方案1】:

您需要创建自己的窗口,代码隐藏包含一个加载的处理程序和一个计时器处理程序,如下所示:

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();

【讨论】:

  • 有哪些可用的 Timer 类型?
【解决方案2】:

System.Windows.MessageBox.Show() 方法有一个重载,它将所有者 Window 作为第一个参数。如果我们创建一个不可见的所有者窗口,然后在指定时间后关闭它,它的子消息框也会关闭。

这是完整的答案:https://stackoverflow.com/a/20098381/2190520

【讨论】:

    【解决方案3】:
    [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
    

    【讨论】:

      【解决方案4】:

      这个库https://github.com/DmitryGaravsky/AutoClosingMessageBox 实现了一个MessageBox,它会在指定时间后自行关闭。

      另请参阅此 stackoverflow 答案https://stackoverflow.com/a/14522952/4856020

      【讨论】:

        猜你喜欢
        • 2014-07-04
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 2014-09-23
        • 1970-01-01
        • 2013-04-14
        • 2021-01-26
        • 2013-12-04
        相关资源
        最近更新 更多