简体   繁体   中英

Automatically close messagebox in C#

I am currently developing an application in C# where I display a MessageBox. How can I automatically close the message box after a couple of seconds?

You will need to create your own Window, with the code-behind containing a loaded handler and a timer handler as follows:

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

You can then make your custom message box appear by calling ShowDialog():

MyWindow w = new MyWindow();
w.ShowDialog();

The System.Windows.MessageBox.Show() method has an overload which takes an owner Window as the first parameter. If we create an invisible owner Window which we then close after a specified time, it's child message box would close as well.

Here is the complete answer: https://stackoverflow.com/a/20098381/2190520

[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

This library https://github.com/DmitryGaravsky/AutoClosingMessageBox implements a MessageBox which closes itself after a specified time.

Also see this stackoverflow answer https://stackoverflow.com/a/14522952/4856020

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM