I need to create a custom MessageBox in C# Framework 3.5 which displays some MesageBoxButtons, and returns the DialogResult value. If there is no user reaction, after a certain timeout time, the MessageBox should close, returning null.
I followed DmitryG's answer here, with minor changes:
static DialogResult? dialogResult_ = null;
public AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons msbb)
{
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
dialogResult_ = MessageBox.Show(text, caption, msbb);
}
public static DialogResult? Show(string text, string caption, int timeout, MessageBoxButtons efb)
{
new AutoClosingMessageBox(text, caption, timeout, efb);
return dialogResult_;
}
void OnTimerElapsed(object state)
{
IntPtr mbWnd = FindWindow("#32770", _caption);
if (mbWnd != IntPtr.Zero)
{
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
}
dialogResult_ = null;
}
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);
To create the MessageBox we only have to call the Show function
AutoClosingMessageBox.Show("Show me sth", "capt", 3000, MessageBoxButtons.AbortRetryIgnore);
This approach does return the dialogResult_ value when the user clicks on a button within the MessageBox, but the WM_Close message doesn't close the MessageBox anymore after the timeout time.
Is this because the MessageBox is still waiting for the Dialog Result? If yes, how can I avoid it? I would like to avoid having to start the Message Box in a new thread and having to kill the thread.