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?
Asked
Active
Viewed 4.1k times
13
-
6Indeed - a timer - and your own custom dialog rather than a MessageBox, otherwise you'll have to start fiddling with sending events to the MessageBox in order to get it to close, I'd imagine. – Will A Dec 06 '10 at 00:36
-
For C++ Check out this https://stackoverflow.com/a/66004457/6219626 – Haseeb Mir Feb 02 '21 at 06:11
4 Answers
12
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();

Greg Sansom
- 20,442
- 6
- 58
- 76
3
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
1
[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

deHaar
- 17,687
- 10
- 38
- 51

user12594936
- 11
- 1
-1
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

datchung
- 3,778
- 1
- 28
- 29