我需要在 C# Framework 3.5 中创建一个自定义 MessageBox,它显示一些 MessageBoxButtons,并返回 DialogResult 值。如果没有用户反应,在一定的超时时间后,MessageBox 应该关闭,返回 null。
我在这里按照 DmitryG 的回答进行了一些细微的更改:
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);
要创建 MessageBox,我们只需要调用 Show 函数
AutoClosingMessageBox.Show("Show me sth", "capt", 3000, MessageBoxButtons.AbortRetryIgnore);
当用户单击 MessageBox 中的按钮时,此方法确实返回 dialogResult_ 值,但 WM_Close 消息在超时时间后不再关闭 MessageBox。
这是因为 MessageBox 仍在等待对话框结果吗?如果是,我该如何避免?我想避免必须在新线程中启动消息框并不得不终止线程。