Friday, February 20, 2015

How to close a MessageBox after several seconds?

Related to: Close a MessageBox after several seconds.
I need to create a message box or Popup which must be visible for specified time and close automatically after then.

There is not inbuilt feature in .net framework to do this. You need to create your custom logic that message box close after a specific time. To do this create a custom message box class which have a timer which close the raised pop message when elapsed time equal to specified time to make it visible to the user.
Here is the custom class:

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

It can be called as below:

AutoClosingMessageBox.Show("Text", "Caption", 1000);

No comments :

Post a Comment