首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

WinForm 訊息方塊 3-5 秒自動關閉的實作方式

     編輯:程式設計綜合問答

需求

在 C# WinForm 專案中,點擊「儲存」按鈕後顯示「儲存成功」訊息方塊,希望 3 到 5 秒後自動關閉,不需使用者手動點擊確定。

方案比較

方案實作難度相容性備註
MessageBoxTimeout (未公開 API) 低 Windows 全版本 微軟未文件化,理論上穩定但非官方支援
自訂 Form 模擬 MessageBox 中 完全可控 最標準、安全、可高度客製化
Timer + FindWindow + SendMessage 高 脆弱 依賴視窗標題/類別名,易受版本/語系影響
Task.Delay + 關閉邏輯 中 需自訂 Form 現代非同步寫法

方案一:使用 MessageBoxTimeout (快速、簡潔)

這是一個存在於 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 秒後自動關閉
}

參考資料:百度百科 MessageBoxTimeout

方案二:自訂 Form (標準、可維護、推薦長期專案)

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,一行搞定。
  • 正式產品/需客製化樣式/長期維護:花 10 分鐘寫一個自訂 Form,乾淨、安全、可擴充(如加入進度條、倒數計時顯示、不同圖示)。

建議團隊建立共用的 MessageHelper.ShowAutoClose(...) 靜態方法,內部封裝自訂 Form 實作,對外提供統一介面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved