MessageBox.Show() 為模態阻塞對話框,無內建自動關閉功能。需在背景執行緒定時尋找視窗並發送關閉訊息。
using System.Runtime.InteropServices;
public class AutoCloseMessageBox
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const uint WM_CLOSE = 0x0010;
}
using System;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class TimedMessageBox
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const uint WM_CLOSE = 0x0010;
public static void Show(string text, string caption, int timeoutMilliseconds)
{
// 背景執行緒啟動定時器
var timer = new System.Windows.Forms.Timer();
timer.Interval = timeoutMilliseconds;
timer.Tick += (sender, e) => {
CloseMessageBox(caption);
timer.Stop();
timer.Dispose();
};
timer.Start();
// 主執行緒顯示 MessageBox (阻塞)
MessageBox.Show(text, caption);
}
private static void CloseMessageBox(string caption)
{
// 依標題尋找視窗 (類別名稱為 "#32770" 為標準對話框)
IntPtr hWnd = FindWindow("#32770", caption);
if (hWnd != IntPtr.Zero)
{
PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}
private void btnShow_Click(object sender, EventArgs e)
{
// 3 秒後自動關閉
TimedMessageBox.Show("此訊息將在 3 秒後自動關閉", "自動關閉提示", 3000);
}
public static DialogResult ShowEx(
string text, string caption,
MessageBoxButtons buttons = MessageBoxButtons.OK,
MessageBoxIcon icon = MessageBoxIcon.Information,
MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1,
int timeoutMs = 5000)
{
var timer = new System.Windows.Forms.Timer();
timer.Interval = timeoutMs;
timer.Tick += (s, e) => { CloseMessageBox(caption); timer.Stop(); timer.Dispose(); };
timer.Start();
return MessageBox.Show(text, caption, buttons, icon, defaultButton);
}
| 方案 | 優點 | 缺點 |
|---|---|---|
| Timer + FindWindow | 零依賴、相容所有 .NET 版本 | 依賴視窗標題唯一性、P/Invoke 脆弱 |
| 自訂 Form 模擬 MessageBox | 完全控制、支援動畫、任意內容 | 開發成本高、需維護樣式一致性 |
| WPF 自訂對話框 | 現代 UI、資料繫結、動畫豐富 | 需 WPF 專案或跨框架整合 |
| 第三方庫 (MaterialDesign, HandyControl) | 開箱即用、美觀 | 引入依賴、授權考量 |
Timer 在 UI 執行緒觸發 Tick,安全呼叫 FindWindow。Invoke 同步。