在 C# WinForm 專案中,點擊「儲存」按鈕後顯示「儲存成功」訊息方塊,希望 3 到 5 秒後自動關閉,不需使用者手動點擊確定。
| 方案 | 實作難度 | 相容性 | 備註 |
|---|---|---|---|
| MessageBoxTimeout (未公開 API) | 低 | Windows 全版本 | 微軟未文件化,理論上穩定但非官方支援 |
| 自訂 Form 模擬 MessageBox | 中 | 完全可控 | 最標準、安全、可高度客製化 |
| Timer + FindWindow + SendMessage | 高 | 脆弱 | 依賴視窗標題/類別名,易受版本/語系影響 |
| Task.Delay + 關閉邏輯 | 中 | 需自訂 Form | 現代非同步寫法 |
這是一個存在於 user32.dll 的未公開函數,行為與 MessageBox 幾乎相同,多了超時參數。
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public static class AutoCloseMessageBox
{
[DllImport("user32.dll", SetLastError = true)]
private static extern int MessageBoxTimeout(
IntPtr hWnd,
string lpText,
string lpCaption,
uint uType,
ushort wLanguageId,
int dwMilliseconds);
public static void Show(string text, string caption, int timeoutMilliseconds)
{
MessageBoxTimeout(IntPtr.Zero, text, caption, 0, 0, timeoutMilliseconds);
}
}
// 使用範例
private void btnSave_Click(object sender, EventArgs e)
{
// ... 儲存邏輯 ...
AutoCloseMessageBox.Show("儲存成功!", "提示", 3000); // 3 秒後自動關閉
}
public partial class AutoCloseForm : Form
{
private readonly Timer _timer;
public AutoCloseForm(string message, string title, int seconds)
{
InitializeComponent();
this.Text = title;
lblMessage.Text = message;
_timer = new Timer { Interval = seconds * 1000 };
_timer.Tick += (s, e) => { _timer.Stop(); this.Close(); };
_timer.Start();
}
// 設計介面:一個 Label (lblMessage) + 可選的按鈕
}
// 呼叫
new AutoCloseForm("儲存成功!", "提示", 3).ShowDialog();
MessageBoxTimeout,一行搞定。建議團隊建立共用的 MessageHelper.ShowAutoClose(...) 靜態方法,內部封裝自訂 Form 實作,對外提供統一介面。