I have seen several requests for timeout message box functionality.
Just sharing some code used in a recent project.
If timeout happens Rtn.ToString() will be "Cancel"
Also check out the help text article on "NTMessageBoxSimple" if you need help finding the window object
Thread th = new Thread(() => {
string Txt = "Message text to display";
string Cap = "Message box caption";
NtMsgResult Mb = new NtMsgResult();
MessageBoxResult Rtn = Mb.Show(Window,Txt,Cap,10000);
Print(Rtn.ToString() );
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
public class NtMsgResult
{
#region Class vars
private string _caption;
private System.Threading.Timer _timeoutTimer;
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);
#endregion
public NtMsgResult(){}
public MessageBoxResult Show(Window win, string text, string caption, int timeout)
{
return Show(win, text, caption, timeout, MessageBoxButton.YesNo, MessageBoxImage.Question) ;
}
public MessageBoxResult Show(Window win, string text, string caption, int timeout, MessageBoxButton Btns, MessageBoxImage Img)
{
_caption = caption;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
null, timeout, System.Threading.Timeout.Infinite);
using(_timeoutTimer)
{
MessageBoxResult Rtn = NTMessageBoxSimple.Show(win,text,caption,Btns,Img);
return Rtn;
}
}
void OnTimerElapsed(object state) {
IntPtr mbWnd = FindWindow(null, _caption); // lpClassName is #32770 for MessageBox
if(mbWnd != IntPtr.Zero)
SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
_timeoutTimer.Dispose();
}
}
