Try the following approach:
AutoClosingMessageBox.Show("Text", "Caption", 1000);
If the AutoClosingMessageBox class AutoClosingMessageBox implemented as follows:
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); using(_timeoutTimer) 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("#32770", _caption);
Update. If you want to get the return value of the underlying MessageBox when the user selects something before the timeout, you can use the following version of this code:
var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo); if(userResult == System.Windows.Forms.DialogResult.Yes) { // do something } ... public class AutoClosingMessageBox { System.Threading.Timer _timeoutTimer; string _caption; DialogResult _result; DialogResult _timerResult; AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); _timerResult = timerResult; using(_timeoutTimer) _result = MessageBox.Show(text, caption, buttons); } public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) { return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result; } void OnTimerElapsed(object state) { IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is
Another update
I checked the YesNo case with the YesNo buttons and found that the WM_CLOSE message sending WM_CLOSE did not work at all.
I will provide a fix in the context of a separate AutoclosingMessageBox library. This library contains a redesigned approach and, I believe, may be useful to someone.
It is also available through the NuGet package :
Install-Package AutoClosingMessageBox
Release Notes (v1.0.0.2):
- API New Show (IWin32Owner) to support most popular scripts (in context # 1 );
- API New Factory () to provide full control over the display of MessageBox;