MessageBox.Show 為阻塞式對話框,無內建自動關閉功能。利用 Timer 定時呼叫 Win32 API FindWindow 尋找視窗並發送 WM_CLOSE 訊息實現定時自動關閉。
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication1 {
public partial class AutoDeleteMessageBox : Form {
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0x10;
public AutoDeleteMessageBox() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) {
StartKiller();
MessageBox.Show("3秒鐘後自動關閉MessageBox視窗", "MessageBox");
}
private void StartKiller() {
Timer timer = new Timer();
timer.Interval = 3000;
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e) {
KillMessageBox();
((Timer)sender).Stop();
}
private void KillMessageBox() {
IntPtr ptr = FindWindow(null, "MessageBox");
if (ptr != IntPtr.Zero) {
PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
}
}
}
FindWindow(null, "MessageBox"):依標題尋找視窗控制碼。PostMessage(hWnd, WM_CLOSE, ...):發送關閉訊息,非阻塞。Timer:在獨立執行緒定時觸發,避免阻塞 UI 主執行緒。MessageBoxEx.ShowWithTimeout(text, caption, timeoutMs)。Task.Delay + async/await 簡化非同步邏輯(.NET 4.5+)。