萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# WinForms 自動關閉 MessageBox:Timer + FindWindow 實作

需求場景

MessageBox.Show() 為模態阻塞對話框,無內建自動關閉功能。需在背景執行緒定時尋找視窗並發送關閉訊息。

核心 API (P/Invoke)


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)開箱即用、美觀引入依賴、授權考量

注意事項

  • 標題必須唯一,避免誤關閉同標題視窗。
  • 多執行緒 UI 操作需注意:Timer 在 UI 執行緒觸發 Tick,安全呼叫 FindWindow。
  • 若 MessageBox 由其他執行緒顯示,需用 Invoke 同步。
  • .NET Core 3.0+ / .NET 5+ 同樣適用。
copyright © 萬盛學電腦網 all rights reserved