Introduction
This article describes a simple extension of the standard messagebox
with a timeout option. This might be very useful if timed events are used to automatically show message boxes. Using the standard messagebox in such cases will result in a lot of messageboxes on top of each other which will be very irritating for users of your application.
Background
I use this class in my application which runs on a 24/7 base. In case of failures of the application, I have to show this to the user. If the user does not see/react to the message presented to him, my application still has to take some action. So, after an optional timeout, the messagebox
is closed.
Using the Code
The code exists of one main class:
and two helper classes:
MsgBoxExtOptions
MsgBoxResultEventArgs
msgBoxExt Usage
msgBoxExt.msgBoxResultEvent +=
new EventHandler<MsgBoxResultEventArgs>(msgBoxExt_msgBoxResultEvent);
int timeout = 5000
bool model = false;
MsgBoxExtOptions options = new MsgBoxExtOptions
("Do you want to close this application?",
"Quit", MsgBoxResultReferences.CLOSE_ON_YES,
MessageBoxButtons.YesNo, MessageBoxIcon.Question, timeout, model);
msgBoxExt.Show(options);
msgBoxExt Class
This class has one public
method. The show
method checks whether there is a messagebox
active. If so: it does nothing if the msgBox
is model and closes it if it is not active.
If timeout > 0, a timeout timer is started.
An native messagebox
is started in a thread:
public static bool Show(MsgBoxExtOptions options)
{
if (_currentOptions != null)
{
if (_currentOptions.model)
{
return false; }
closeMessageBox(_currentOptions.caption);
}
_currentOptions = options;
if (options.timeout > 0)
{
timeoutTimer = new System.Windows.Forms.Timer();
timeoutTimer.Tick += new EventHandler(timeoutTimer_Tick);
timeoutTimer.Interval = options.timeout;
timeoutTimer.Enabled = true;
}
msgBoxThread = new Thread(new ThreadStart(startMsgBoxThread));
msgBoxThread.IsBackground = true;
msgBoxThread.Start();
return true;
}
On timer tick, the current messagebox
is closed and a result event is generated:
private static void timeoutTimer_Tick(object sender, EventArgs e)
{
closeMessageBox(_currentOptions.caption);
onMsgBoxResultEvent(_currentOptions.resultReference, DialogResult.None);
_currentOptions = null;
}
closemessagebox()
makes use of killwindow()
which in its turn makes use of two native functions: findwindow
and sendmessage
to destroy the current dialog.
private static void KillWindow(string className, string title)
{
IntPtr handle = FindWindow(className, title);
SendMessage(handle, WM_NCDESTROY, (IntPtr)0, (IntPtr)0);
}
History
- 12th July, 2010: Initial post